如何让一个线程等待另一个线程的一部分完成?

How to make one thread wait for a part of another thread to finish?

在名为 Record 的函数中,我创建了一个线程。让线程函数称为ThreadFn。 我希望 Record 等到 ThreadFn 中从 ThreadFn 开头开始的一段代码完成。 我该怎么做呢?我一直在尝试使用 Mutex。但是我不确定在哪里放CreateMutex和放ReleaseMutex。

我尝试了以下方法。但它不起作用。 有一个全局变量

HANDLE ghMutex = NULL;

ThreadFn 内部: 开头

ghMutex = CreateMutex(NULL, FALSE, NULL); 

代码块完成后,

ReleaseMutex(ghMutex);

内幕:

Create the thread
WaitForSingleObject(ghMutex, INFINITE);
Close thread handle
CloseHandle(ghMutex);

您可以为此使用简历。 Condition Variable

mutex m;
bool ready = false;
condition_variable cv;

Record() {
    //some code

    //create thread
    createThread(Threadfn());


    //get the lock
    m.lock();
    //waits until it gets a signal call     
    while (!ready) cv.wait(m);

   //continues code
}

Threadfn() {

    //get the lock
    m.lock();

    // run code

    // tell Record that it can continue again
    ready = true;
    m.unlock();
    cv.notify_one();

}

发生的事情是 Record() 锁定了一个互斥锁并挂在 while (!ready) cv.wait(lck) 上,直到 Threadfn() 发出信号。