暂停并恢复另一个C ++线程

时间:2013-03-19 14:04:27

标签: c++ multithreading winapi

我有一个带有两个线程的C ++代码。在线程2中的事件“A”之后,线程1应该暂停(暂停),在线程2中执行更多任务(比如事件“B”),最后应该恢复线程1。有没有办法做到这一点?

我的代码看起来像这样:

HANDLE C;
DWORD WINAPI A (LPVOID in)
{
    while(1){
        // some operation
    }
    return 0;
}

DWORD WINAPI B (LPVOID in)
{
    while(1){

        //Event A occurs here

        SuspendThread (C);

        //Event B occurs here

        ResumeThread (C);
        }
    return 0;
}

int main()
{
    C = CreateThread (NULL, 0, A, NULL, 0, NULL);
    CreateThread (NULL, 0, B, NULL, 0, NULL);
    return 0;
}

2 个答案:

答案 0 :(得分:9)

您好我有一个例子,我从cpp参考中受到启发。 该示例使用C ++ 11,因为这个问题没有标记为win32,而是c ++和多线程我发布了一些内容。

首先是原始链接。

http://en.cppreference.com/w/cpp/thread/sleep_for

现在我的代码解决了这个问题。

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

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void ThreadB_Activity()
{
    // Wait until ThreadA() sends data
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return ready;});
    }

    std::cout << "Thread B is processing data\n";
    data += " after processing";
    // Send data back to ThreadA through the condition variable
    {
        std::lock_guard<std::mutex> lk(m);
        processed = true;
        std::cout << "Thread B signals data processing completed\n";
    }
    cv.notify_one();
}


void ThreadA_Activity()
{
    std::cout<<"Thread A started "<<std::endl;
    data = "Example data";
    // send data to the worker thread
    {
        std::lock_guard<std::mutex> lk(m);
        ready = true;
        std::cout << "Thread A signals data are ready to be processed\n";
    }
    cv.notify_one();//notify to ThreadB that he can start doing his job

    // wait for the Thread B
    {
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return processed;});
    }
    std::cout << "Back in Thread A , data = " << data << '\n';

    std::this_thread::sleep_for( std::chrono::milliseconds( 1000 ));
    std::cout<<"end of Thread A"<<std::endl;
}


int main()
{
    std::thread ThreadB(ThreadB_Activity);
    std::thread ThreadA(ThreadA_Activity);

    ThreadB.join();
    ThreadA.join();

    std::cout << "Back in main , data = " << data << '\n';
    return 0;
}

希望有所帮助,欢迎提出任何意见: - )

答案 1 :(得分:0)

由于您似乎使用的是win32,因此可以使用event

如果你想在pthreads中做类似的事情,那就是example here

在这两种情况下,线程A将测试条件/事件(如果设置则等待,或者如果不是则等待),线程B将设置并清除条件/事件。请注意,您可能还需要在线程A和B之间使用互斥锁,具体取决于它们正在执行的操作,它们是否会相互损坏?