线程 c++防止价值改变

发布于 2024-11-03 09:00:45 字数 522 浏览 0 评论 0原文

我使用 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)

当线程内的全局值更改时,我不希望其他线程执行 并再次更改该值 例如 function(a,b){

if(该线程发生了某些事情) value = 5;

//如果什么也没发生 值=1; ?

如果一个线程获得值 5,那么我不希望其他线程干扰该值并使其返回到 1。我该如何执行此操作 谢谢。

也许做到这一点的方法是使用 boost:mutex 但我没有看到这样做有任何好处,因为这个值只是找到的 在 return 语句之前,我很可能使用了 boost join_all()。但这会降低效率。

I am using boosthread to create 3 threads calling the same function each time with different arguments being passed.
E.g. 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)

When a global value within the thread is changed I do not want the other threads to execute
and change the value again
E.g function(a,b){

if(something happened for that thread) value = 5;

//if nothing happened
value = 1;
}

If one thread gets a value of 5 then I do not want the other threads to interfere with that value and make it go back to 1. How can I do this? Thanks.

Maybe the way to do this is to use boost:mutex but I do not see any gain in doing so because this value is found just
before the return statement and I might well have used boost join_all(). But this would be less efficient.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滿滿的愛 2024-11-10 09:00:45

我有一个例子可以帮助你。
它使用 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;
}

希望有帮助,如果没有回答问题请随时告诉我

I have one example that will help you.
It uses C++11 but can be transposed to Boost easily.

the algorithm is simple, it is made of two main parts:

  1. Launches three threads
  2. Joins them(waits for them to finish)

What each thread does:

  1. Does some work
  2. Inititalizes a variable if it has never been initialized before (FirstThreadToFinish)

How does the unique intializer function works.
1.uses a mutex to prevent multiple access to shared variables (guarantees that ths function is only acceesed by one thread at a time)
2.If the variables has not been initialized it initializes it with the name of the thread and sets the boolean to true (variable initialized)
3. otherwise does nothing

#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;
}

Hope that helps, feel free to tell me if does not answer the question

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文