我有一個例子會幫助你。它使用C++ 11,但可以輕鬆轉換爲Boost。
的算法很簡單,它是由兩個主要部分組成:
- 推出三個線程
- 加入他們(等待他們完成)
每個線程做些什麼:
- 做了一些工作
- 初創一個變量,如果它從未初始化過(FirstThreadToFinish)
獨特的初始化函數是如何工作的。 1.使用互斥鎖來防止對共享變量的多重訪問(保證該函數一次僅由一個線程加以確認) 2.如果變量尚未初始化,則使用線程的名稱對其進行初始化並設置布爾爲true(變量初始化) 3.否則什麼也不做
#include "stdafx.h"
#include <thread>
#include <chrono>
#include <mutex>
#include <iostream>
#include <string>
using namespace std;
mutex m;//to synchronize the data properly
string FirstThreadToFinish;
bool IsInitialized;
//This function is called by the main thread: does the work and initializes the variable only once
int MyThreadFunction(int Duration, const string & ThreadName);
//this function does some work (put here what your thread is really supposed to do)
int DoSomeWork(int Duration);
//this function initializes the variable only once and does nothing otherwise
int InitializeVariableOnce(int Duration, const string & ThreadName);
//this function initializes the variable only once and does nothing otherwise
int InitializeVariableOnce(int Duration, const string & ThreadName)
{
std::lock_guard<mutex> l(m);
if (!IsInitialized)
{
FirstThreadToFinish=ThreadName;
IsInitialized=true;
cout<<"FirstThreadToFinish= "<<ThreadName<< ", IsInitialized= "<<IsInitialized<<endl;
}
return 0;
}
//this function does some work (put here what your thread is really supposed to do)
int DoSomeWork(int Duration)
{
std::this_thread::sleep_for(std::chrono::seconds(Duration));
return 0;
}
int MyThreadFunction(int Duration, const string & ThreadName)
{
DoSomeWork(Duration);
InitializeVariableOnce(Duration, ThreadName);
return 0;
}
int main()
{
//at the begining nothing is initialized
FirstThreadToFinish="Uninitialized";
IsInitialized=false;
cout<< "FirstThreadToFinish= "<<FirstThreadToFinish << ", IsInitalized="<<IsInitialized<<endl;
cout<<"Now launching 3 threads= "<<endl;
thread MyAThread(MyThreadFunction,1,"AThread");
thread MyBThread(MyThreadFunction,2,"BThread");
thread MyCThread(MyThreadFunction,3,"CThread");
MyAThread.join();
MyBThread.join();
MyCThread.join();
return 0;
}
希望幫助,請隨時告訴我,如果不回答這個問題
嘗試把修改後的值到隊列中。在插入時確保它不在隊列中,如果它已經存在,則丟棄新獲得的值,這樣你將得到一個不應該改變的值,並且注意隊列必須在鎖定語句中,即互斥量爲 – 2011-04-25 16:50:58
讓我感謝你Wajih – tester 2011-04-25 18:30:01
np隊友。希望它爲你工作。 – 2011-04-26 15:47:15