Poco 线程同步问题

Poco thread synchronization issue

本文关键字:问题 同步 线程 Poco      更新时间:2023-10-16

以下是了解互斥锁和线程同步的示例 Poco 线程程序。仍然看到同一程序的不同输出。

#include "Poco/ThreadPool.h"
#include "Poco/Thread.h"
#include "Poco/Runnable.h"
#include "Poco/Mutex.h"
#include <iostream>
#include <unistd.h>
using namespace std;
class HelloRunnable: public Poco::Runnable
{
    public:
        static int a;
        HelloRunnable(){
        }
        HelloRunnable(unsigned long n):_tID(n){
        }
        void run()
        {
            Poco::Mutex::ScopedLock lock(_mutex);
            std::cout << "==>> In Mutex thread " << _tID << endl;
            int i;
            for (i=0;i<50000;i++)
            {
                a = a+1;
            }
            Poco::Mutex::ScopedLock unlock(_mutex);
        }
    private:
        unsigned long _tID;
        Poco::Mutex _mutex;
};
int HelloRunnable::a = 0;
int main(int argc, char** argv)
{
    Poco::Thread thread1("one"), thread2("two"), thread3("three");
    HelloRunnable runnable1(thread1.id());
    HelloRunnable runnable2(thread2.id());
    HelloRunnable runnable3(thread3.id());
    thread1.start(runnable1);
    thread2.start(runnable2);
    thread3.start(runnable3);
    thread1.join();
    thread2.join();
    thread3.join();
    cout << "****>> Done and a: " << HelloRunnable::a  << endl;
    return 0;
}

获取输出,如下所示:

输出1:

==>> 在互斥线程 1
中==>> 在互斥线程 2
中==>> 在互斥线程 3
中>> 完成和 a: 142436

输出2:

==>> 在互斥线程 2==>> 在互斥线程 3

==>> 在互斥线程 1
中>> 完成和 a: 143671

输出3:

==>> 在互斥线程 2
中==>> 在互斥线程 3
中==>> 在互斥线程 1
中>> 完成和 a:150000

我总是期待OutPut3作为结果。上述程序有什么问题?

互斥锁是类的非静态成员变量,这意味着类的每个实例都有自己的互斥锁。如果要同步,则需要在线程之间共享互斥锁。你需要让它static.

同样在run函数中,变量unlock不执行任何操作。对象lock将在超出范围时解锁互斥锁,即函数返回时。