2013-04-29 39 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; 
} 

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

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