[英]Thread c++ Prevent value from changing
我正在使用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)
當更改線程內的全局值時,我不希望其他線程執行並再次更改該值,例如Eg function(a,b){
if(該線程發生了什么)值= 5;
//如果沒有任何反應,則值= 1; }
如果一個線程的值是5,那么我不希望其他線程干擾該值並使它回到1。我該怎么做? 謝謝。
也許這樣做的方法是使用boost:mutex,但這樣做沒有任何好處,因為此值是在return語句之前找到的,我可能已經使用了boost join_all()。 但這會降低效率。
我有一個例子可以為您提供幫助。 它使用C ++ 11,但可以輕松轉換為Boost。
該算法很簡單,它由兩個主要部分組成:
每個線程的作用:
獨特的初始化器功能如何工作。 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;
}
希望對您有幫助,請隨時告訴我是否未回答問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.