2013-03-19 59 views
7

我有一個C++代碼,其中有兩個線程。在線程2中的事件'A'之後,線程1應該暫停(掛起),線程2中要執行更多的任務(比如事件'B'),最後線程1應該被恢復。有沒有辦法做到這一點?暫停和恢復一個C++線程在另一個

我的代碼看起來是這樣的:

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; 
} 
+0

你正在做的,現在,什麼問題? – deepmax 2013-03-19 14:09:51

+5

隨機死鎖,毫無疑問。 – 2013-03-19 14:56:56

回答

0

既然你似乎是使用Win32,你可以使用一個event

如果你想要做的並行線程類似的東西有一個example here

在這兩種情況下,線程A都會測試一個條件/事件(並且等待它是否被設置,否則繼續),並且線程B將設置並清除條件/事件。請注意,您可能還需要線程A和B之間的互斥,具體取決於他們在做什麼,他們是否可以互相破壞?

8

嗨我有一個例子,我從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; 
} 

希望幫助,任何意見,歡迎:-)