Poco 线程同步问题
Poco thread synchronization issue
以下是了解互斥锁和线程同步的示例 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
将在超出范围时解锁互斥锁,即函数返回时。
相关文章:
- 线程过程中的线程同步问题
- 使用 qt 和 opengl、定时精度和垂直同步问题、c++ 显示图像
- C++11 中 3 个线程和 2 个共享资源的同步问题
- 队列的同步问题
- C++ 获取同步密钥状态状态问题
- Google 日历与订阅日历"Remember the milk"同步问题
- Qt QState机器同步问题:初始状态未在启动信号上设置
- POSIX线程同步和/或pthread_create()参数传递问题
- 线程同步问题
- MP3帧头检测FFF/FFE同步问题
- 线程同步问题
- 在同步问题中,弱指针可以代替互斥锁或临界区吗?
- 与MPI-2单向通信同步单个int值的问题
- 同步MPI-2单向通信中的顺序问题
- QStateMachine的同步问题
- c++并发、同步设计,避免多次执行问题
- 录制视频和音频-同步问题
- Poco 线程同步问题
- Boost Asio:关于教程的一些问题(同步日间服务器/客户端)
- Turbo c++文件同步问题