多线程暂停/恢复

主线程使用线程组进行搜索。第一个解决方案(test1)通常是创建,等待-join()和销毁线程。这有效,但有开销。我尝试使用互斥锁和condition_variable,但这不起作用。尤其是对于数字搜索线程> 1。

我的代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>

using namespace std;

const int NThr = 2;

struct InterchangeData {
    bool endflag=false;
    mutex chg_mutex;
    condition_variable condition;
};
InterchangeData data;

bool execute1(InterchangeData* xchgData) {
    for (int i=0; i<10; i++) {
        if (xchgData->endflag) return false;
        this_thread::sleep_for(chrono::milliseconds(rand()%10 +1 ));
        if (rand()%100 == 50) {
            lock_guard<mutex> lock(xchgData->chg_mutex);
            if (!xchgData->endflag) {
                printf("found!");
                xchgData->endflag = true;
                return true;
            }
        }
    }
    return false;
}

bool execute2(InterchangeData* xchgData) {
    while (true) {
        {
            unique_lock<mutex> lock(xchgData->chg_mutex);
            xchgData->condition.wait(lock);
        }
        int ret=2;
        if (xchgData->endflag) ret=0;
        if (execute1(xchgData)) ret=1;
        {
            unique_lock<mutex> lock(xchgData->chg_mutex);
            xchgData->condition.notify_one();
            this_thread::sleep_for(chrono::milliseconds(1));
            if (ret==0) return false;
            else if (ret==1) return true;
        }
    }
}

vector<thread*> threads;
typedef bool (*functype)(InterchangeData*);

void start(functype execute) {
    for (int i=0; i<NThr; i++) {
        auto t = new thread(execute,&data);
        threads.push_back(t);
    }
}

void stop() {
    for (auto t : threads) {
        t->join();
        delete t;
    }
    threads.clear();
}


void test1() {
    for (int i=0; i<10; i++) {
        start(&execute1);
        stop();
    }
}

void test2() {
    start(&execute2);
    this_thread::sleep_for(chrono::milliseconds(100));
    for (int i=0; i<10; i++) {
        {
            unique_lock<mutex> lock(data.chg_mutex);
            data.condition.notify_one();
            this_thread::sleep_for(chrono::milliseconds(1));
        }
        {
            unique_lock<mutex> lock(data.chg_mutex);
            data.condition.wait(lock);
        }
    }
    {
        unique_lock<mutex> lock(data.chg_mutex);
        data.condition.notify_one();
        this_thread::sleep_for(chrono::milliseconds(1));
    }
    stop();
}

int main() {
    test2();
    return 0;
}

问题:可以使用condition_variable,unique_lock和wait / notify_one快速暂停/恢复执行功能和主线程吗?

iCMS 回答:多线程暂停/恢复

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1659822.html

大家都在问