2011-04-25 78 views
1

我正在使用boosthread創建3個線程,每次調用不同的參數都會傳遞相同的函數。 例如1/thread.add(function,int a1,std :: string b),thread.add(function,int a2,std :: string b), thread.add(function,int a3,std :: string b) ,thread.add(function,int a4,std :: string b)線程C++防止更改值

當線程中的全局值發生變化時,我不希望其他線程執行 並再次更改值 例如,function(a, b){

if(發生該線程的事情)value = 5;

//如果什麼都沒發生 value = 1; }

如果一個線程獲得5的值,那麼我不希望其他線程干擾該值並使其回到1.我該怎麼做?謝謝。

也許這樣做的方法是使用boost:mutex,但我沒有看到這樣做的任何收益,因爲在返回語句之前發現該值只是 ,我可能已經使用boost join_all()。但是這會效率不高。

+0

嘗試把修改後的值到隊列中。在插入時確保它不在隊列中,如果它已經存在,則丟棄新獲得的值,這樣你將得到一個不應該改變的值,並且注意隊列必須在鎖定語句中,即互斥量爲 – 2011-04-25 16:50:58

+1

讓我感謝你Wajih – tester 2011-04-25 18:30:01

+0

np隊友。希望它爲你工作。 – 2011-04-26 15:47:15

回答

0

我有一個例子會幫助你。它使用C++ 11,但可以輕鬆轉換爲Boost。

的算法很簡單,它是由兩個主要部分組成:

  1. 推出三個線程
  2. 加入他們(等待他們完成)

每個線程做些什麼:

  1. 做了一些工作
  2. 初創一個變量,如果它從未初始化過(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; 
} 

希望幫助,請隨時告訴我,如果不回答這個問題