簡體   English   中英

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:

== >>在Mutex線程1中
== >>在Mutex線程2中
== >>在Mutex線程3中
**** >>完成並發送:142436

OUTPUT2:

== >>在Mutex線程2中== >>在Mutex線程3中

== >>在Mutex線程1中
**** >>和a:143671

OUTPUT3:

== >>在Mutex線程2中
== >>在Mutex線程3中
== >>在Mutex線程1中
**** >>完成並答:150000

我一直期待OutPut3作為結果。 以上程序有什么問題?

互斥鎖是該類的非靜態成員變量,這意味着該類的每個實例將具有其自己的互斥鎖。 如果要同步,則互斥鎖需要在線程之間共享。 您需要使其static

同樣在run功能中,變量unlock不執行任何操作。 當對象lock超出范圍時,即函數返回時,對象lock將對其解鎖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM