以下是Sample 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;
}
获得如下输出:
==&GT;&GT;在Mutex线程中1
==&GT;&GT;在Mutex线程中2
==&GT;&GT;在互斥线程3中
****&GT;&GT;完成和a:142436
==&GT;&GT;在Mutex线程2 ==&gt;&gt;在Mutex线程3中
==&GT;&GT;在Mutex线程中1
****&GT;&GT;完成并且:a:143671
==&GT;&GT;在Mutex线程中2
==&GT;&GT;在互斥线程3中
==&GT;&GT;在Mutex线程中1
****&GT;&GT;完成和a:150000
我总是期待OutPut3成为结果。上述课程有什么问题?
答案 0 :(得分:4)
互斥锁是类的非静态成员变量,这意味着类的每个实例都有自己的互斥锁。如果要进行同步,则需要在线程之间共享互斥锁。你需要把它static
。
同样在run
函数中,变量unlock
没有做任何事情。对象lock
将在超出函数返回范围时解锁互斥锁。