gpt4 book ai didi

c++ - 同步两个线程在彼此之间传递事件

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:46 24 4
gpt4 key购买 nike

我是 Windows C++ 编程的新手。请看下面我想让两个线程同步的代码。第一个线程应该打印“Hello”,然后将控制/事件传递给第二个线程。不知道该怎么做。截至目前,我正在使用 Sleep(1000)。但是,如果我不使用 Sleep,它会导致未定义的行为。请帮助...

#include <windows.h>
#include <process.h>
#include <iostream>

void thread1(void*);
void thread2(void*);

int main(int argc, char **argv) {
_beginthread(&thread1,0,(void*)0);
_beginthread(&thread2,0,(void*)0);
Sleep(1000);
}

void thread1(void*)
{
std::cout<<"Hello "<<std::endl;
}
void thread2(void*)
{
std::cout<<"World"<<std::endl;
}

最佳答案

问题是你问的问题真的没有意义。多个线程被设计为同时运行,而您正试图玩一个将责任从一个线程推给另一个线程以获得顺序序列化行为的游戏。这就像使用一个非常复杂的工具并询问它如何解决通常非常简单的问题。

但是,多线程是一个非常重要的学习主题,因此我会尽力回答您的需求。

首先,我建议使用新的标准 C++11 函数和库。对于 Windows,您可以下载 Visual Studio 2012 Express Edition一起玩。

有了它,您可以使用 std::thread、std::mutex 和许多 [但不是全部] 其他 C++11 好东西(如 std::condition_variable)。

要解决您的问题,您确实需要一个条件变量。这让您可以向另一个线程发出信号,表明已经为他们准备好了:

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

static std::atomic<bool> ready;
static std::mutex lock;
static std::condition_variable cv;

// ThreadOne immediately prints Hello then 'notifies' the condition variable
void ThreadOne()
{
std::cout << "Hello ";
ready = true;
cv.notify_one();
}

// ThreadTwo waits for someone to 'notify' the condition variable then prints 'World'
// Note: The 'cv.wait' must be in a loop as spurious wake-ups for condition_variables are allowed
void ThreadTwo()
{
while(true)
{
std::unique_lock<std::mutex> stackLock(lock);
cv.wait(stackLock);
if(ready) break;
}
std::cout << "World!" << std::endl;
}

// Main just kicks off two 'std::thread's. We must wait for both those threads
// to finish before we can return from main. 'join' does this - its the std
// equivalent of calling 'WaitForSingleObject' on the thread handle. its necessary
// to call join as the standard says so - but the underlying reason is that
// when main returns global destructors will start running. If your thread is also
// running at this critical time then it will possibly access global objects which
// are destructing or have destructed which is *bad*
int main(int argc, char **argv)
{
std::thread t1([](){ThreadOne();});
std::thread t2([](){ThreadTwo();});
t1.join();
t2.join();
}

关于c++ - 同步两个线程在彼此之间传递事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17029866/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com