Vig*_*igo 7 c++ winapi multithreading
我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
Gab*_*iel 10
嗨,我有一个例子,我从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;
}
Run Code Online (Sandbox Code Playgroud)
希望有所帮助,欢迎任何评论:-)