Poco线程同步问题

Kra*_*thi 0 c++ multithreading synchronization mutex poco

下面是示例 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;
}
Run Code Online (Sandbox Code Playgroud)

获取输出如下:

输出 1:

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

输出 2:

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

==>> 在互斥锁线程 1 中
****>> 完成,a:143671

输出 3:

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

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

Som*_*ude 5

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

同样在run函数中,变量unlock不做任何事情。当对象lock超出范围时,即函数返回时,对象将解锁互斥锁。