2013-04-29 76 views
1

我試着解決以下問題,我知道有多種解決方案,但我正在尋找最優雅的方式(少代碼)來解決它。C++以最優雅的方式同步線程

我有4個線程,其中3個嘗試在無限循環中向易失性整數變量寫入唯一值(0,1或2),第4個線程嘗試讀取此變量的值並打印stdout的值也在無限循環中。

我想在線程之間進行同步,以便寫入0的線程將被運行,然後是「打印」線程,然後是寫入1,然後再次打印線程的線程,如此等等... 因此,最後我期望看到在「打印」線程的輸出是一個零序列,然後序列1,然後2,然後0,依此類推...

什麼是最優雅,最簡單這些線程之間的同步方式。

這是程序代碼:

volatile int value; 
int thid[4]; 

int main() { 
    HANDLE handle[4]; 
    for (int ii=0;ii<4;ii++) { 
     thid[ii]=ii; 
     handle[ii] = (HANDLE) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)     ThreadProc, &thid[ii], 0, NULL); 
    } 
    return 0; 
} 

void WINAPI ThreadProc(LPVOID param) { 
    int h=*((int*)param); 

    switch (h) { 
     case 3: 
      while(true) { 
       cout << value << endl; 
      } 
      break; 
     default: 
      while(true) { 
       // setting a unique value to the volatile variable 
       value=h; 
      } 
      break; 
    } 
} 
+3

爲什麼不使用C++ 11和'atomic'? – Walter 2013-04-29 11:46:25

+1

對於您希望的訂購要求,您應該使用C++ 11 std :: condition_variable和std :: mutex。 – 2013-04-29 12:02:26

+0

原子本身沒有幫助,你需要一些東西來阻塞線程0並等待線程3處理完數據。這需要某種相互鎖定模式。 – 2013-04-29 12:04:31

回答

0

如果你想同步線程,然後使用同步對象來保存每個線程在「乒乓」或「滴答滴答「模式。 在C++ 11中,您可以使用條件變量,示例here顯示的內容與您要求的內容類似。

+0

這不是這種類型的問題,因爲在這裏你需要控制調度螞蟻將它設置爲這個順序:線程0,線程3,線程1,線程3,線程2,線程3,線程0,線程3等...... – Hawk89 2013-05-10 07:33:24

+0

是的,所以它不完全相同,但它的基本原理是一樣的。 – 2013-05-10 07:51:28

0

您的問題可以通過生產者消費者模式來解決。 我從維基百科獲得靈感,所以這裏是鏈接,如果你想了解更多的細節。

https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

我使用一個隨機數生成器生成的揮發性可變的,但你可以改變的部分。

下面是代碼:它可以在風格方面得到改進(使用C++ 11用於隨機數),但它產生了您的期望。

#include <iostream> 
#include <sstream> 
#include <vector> 
#include <stack> 
#include <thread> 
#include <mutex> 
#include <atomic> 
#include <condition_variable> 
#include <chrono> 
#include <stdlib.h>  /* srand, rand */ 
using namespace std; 

//random number generation 
std::mutex mutRand;//mutex for random number generation (given that the random generator is not thread safe). 
int GenerateNumber() 
{ 
    std::lock_guard<std::mutex> lk(mutRand); 
    return rand() % 3; 
} 

// print function for "thread safe" printing using a stringstream 
void print(ostream& s) { cout << s.rdbuf(); cout.flush(); s.clear(); } 

//  Constants 
// 
const int num_producers = 3;    //the three producers of random numbers 
const int num_consumers = 1;    //the only consumer 
const int producer_delay_to_produce = 10; // in miliseconds 
const int consumer_delay_to_consume = 30; // in miliseconds 

const int consumer_max_wait_time = 200;  // in miliseconds - max time that a consumer can wait for a product to be produced. 

const int max_production = 1;    // When producers has produced this quantity they will stop to produce 
const int max_products = 1;    // Maximum number of products that can be stored 

// 
//  Variables 
// 
atomic<int> num_producers_working(0);  // When there's no producer working the consumers will stop, and the program will stop. 
stack<int> products;      // The products stack, here we will store our products 
mutex xmutex;        // Our mutex, without this mutex our program will cry 

condition_variable is_not_full;    // to indicate that our stack is not full between the thread operations 
condition_variable is_not_empty;   // to indicate that our stack is not empty between the thread operations 

// 
//  Functions 
// 

//  Produce function, producer_id will produce a product 
void produce(int producer_id) 
{ 
    while (true) 
    { 
     unique_lock<mutex> lock(xmutex); 
     int product; 

     is_not_full.wait(lock, [] { return products.size() != max_products; }); 
     product = GenerateNumber(); 
     products.push(product); 

     print(stringstream() << "Producer " << producer_id << " produced " << product << "\n"); 
     is_not_empty.notify_all(); 
    } 

} 

//  Consume function, consumer_id will consume a product 
void consume(int consumer_id) 
{ 
    while (true) 
    { 
     unique_lock<mutex> lock(xmutex); 
     int product; 

     if(is_not_empty.wait_for(lock, chrono::milliseconds(consumer_max_wait_time), 
       [] { return products.size() > 0; })) 
     { 
       product = products.top(); 
       products.pop(); 

       print(stringstream() << "Consumer " << consumer_id << " consumed " << product << "\n"); 
       is_not_full.notify_all(); 
     } 
    } 

} 

//  Producer function, this is the body of a producer thread 
void producer(int id) 
{ 
     ++num_producers_working; 
     for(int i = 0; i < max_production; ++i) 
     { 
       produce(id); 
       this_thread::sleep_for(chrono::milliseconds(producer_delay_to_produce)); 
     } 

     print(stringstream() << "Producer " << id << " has exited\n"); 
     --num_producers_working; 
} 

//  Consumer function, this is the body of a consumer thread 
void consumer(int id) 
{ 
     // Wait until there is any producer working 
     while(num_producers_working == 0) this_thread::yield(); 

     while(num_producers_working != 0 || products.size() > 0) 
     { 
       consume(id); 
       this_thread::sleep_for(chrono::milliseconds(consumer_delay_to_consume)); 
     } 

     print(stringstream() << "Consumer " << id << " has exited\n"); 
} 

// 
//  Main 
// 

int main() 
{ 
     vector<thread> producers_and_consumers; 

     // Create producers 
     for(int i = 0; i < num_producers; ++i) 
       producers_and_consumers.push_back(thread(producer, i)); 

     // Create consumers 
     for(int i = 0; i < num_consumers; ++i) 
       producers_and_consumers.push_back(thread(consumer, i)); 

     // Wait for consumers and producers to finish 
     for(auto& t : producers_and_consumers) 
       t.join(); 
     return 0; 
} 

希望幫助,告訴我,如果你需要更多的信息,或者如果你有什麼不同意:-)

和良好的巴士底日到所有法國人!