Home > Mobile >  C Async Threads
C Async Threads

Time:10-01

I'm very confused with std::thread and std::async. Here is my code:

#include <vector>
#include <thread>
#include <mutex>

std::vector<int> myvector = {};
std::mutex mu;
int result;

void samplefunc(int a, int& result){
    result = 2 * a;
}

void func1(){
    while(true){
        std::unique_lock locker(mu);
        locker.lock();
        std::vector<int> temp = myvector;
        locker.unlock();
        if(myvector.size() > 0){
            samplefunc(myvector.at(0),result);
            myvector.clear();
        }else{
            samplefunc(0,result);
        }
    }
}

void func2(){
    while(true){
        //do complex things, suppose after complex calculations we have result dummy which is type int
        int dummy = 0;
        std::unique_lock locker(mu);
        locker.lock();
        myvector.push_back(dummy);
        locker.unlock();
    }
}

int main(){
    std::thread t1(func1);
    std::thread t2(func2);
    t1.join();
    t2.join();
}

What I want to do is very simple. We have two threads which should run in parallel (i.e. they don't have to wait on each other). However, thread t1 is supposed to change its behaviour if thread t2 puts some integer in a shared vector. Does the code given above achieve this, or should we use std::async, std::future, etc?

CodePudding user response:

If the shared data is properly synchronized, it is fine for modification from one thread on the shared data to affect computation using that data in separate thread. But you haven't locked myvector sufficiently. The lock has to surround all reading steps on the shared data. In func1, you release the lock too soon.

  • Related