2010-11-05 68 views
1

所以我有一個簡單的cpp文件。只有一個主函數和3個int a-la公共變量。比如:哪裏可以獲得簡單的Boost線程管理示例?

int a; 
    int b; 
    int c; 
    void main() 
    { 
     startThredA(); 
     startThredB(); 
     while(1) 
    { 
     c = a + b; 
     printf(c); 
    } 
    } 

我想創造2個A和B,其中一個應該爲A產生隨機值,另一個爲B產生一個隨機值。如何做這樣的事情?

+2

這是'INT main',不'void'。 – GManNickG 2010-11-05 01:11:15

+0

哪一部分[Boost.Thread(http://www.boost.org/doc/libs/1_44_0/doc/html/thread/thread_management.html)文檔的你還不明白嗎? – 2010-11-05 01:22:00

+0

@Sam - 我不明白它只是一個沒有任何例子的函數和類的列表。這幾乎不是一種清晰的模式,使得入場條件高於它應該是。 – 2010-11-05 01:37:45

回答

3

這裏是一個小而簡單的例子。它的嘗試,似乎工作正常。

#include <iostream> 
#include <boost/thread.hpp> 

namespace this_thread = boost::this_thread; 

int a = 0; 
int b = 0; 
int c = 0; 

class BaseThread 
{ 
public: 
    BaseThread() 
     { } 
    virtual ~BaseThread() 
     { } 

    void operator()() 
    { 
     try 
     { 
      for (;;) 
      { 
       // Check if the thread should be interrupted 
       this_thread::interruption_point(); 

       DoStuff(); 
      } 
     } 
     catch (boost::thread_interrupted) 
     { 
      // Thread end 
     } 
    } 

protected: 
    virtual void DoStuff() = 0; 
}; 

class ThreadA : public BaseThread 
{ 
protected: 
    virtual void DoStuff() 
    { 
     a += 1000; 
     // Sleep a little while (0.5 second) 
     this_thread::sleep(boost::posix_time::milliseconds(500)); 
    } 
}; 

class ThreadB : public BaseThread 
{ 
protected: 
    virtual void DoStuff() 
    { 
     b++; 
     // Sleep a little while (0.5 second) 
     this_thread::sleep(boost::posix_time::milliseconds(100)); 
    } 
}; 

int main() 
{ 
    ThreadA thread_a_instance; 
    ThreadB thread_b_instance; 

    boost::thread threadA = boost::thread(thread_a_instance); 
    boost::thread threadB = boost::thread(thread_b_instance); 

    // Do this for 10 seconds (0.25 seconds * 40 = 10 seconds) 
    for (int i = 0; i < 40; i++) 
    { 
     c = a + b; 
     std::cout << c << std::endl; 

     // Sleep a little while (0.25 second) 
     this_thread::sleep(boost::posix_time::milliseconds(250)); 
    } 

    threadB.interrupt(); 
    threadB.join(); 

    threadA.interrupt(); 
    threadA.join(); 
} 
2

有一系列文章starting here,應該給你一些初步的指針。作者主要負責牧養boost.thread到C++ 0x。

列表的物品的:

在多線程的C++ 0x 1部分:啓動線程

在多線程的C++ 0x第2部分:啓動與功能對象的線程和參數

在多線程C++ 0x第3部分:啓動具有成員函數和參考參數的線程

C++中的多線程0x 0x第4部分:保護共享數據

在多線程的C++ 0x第5部分:柔性鎖定用的std :: unique_lock <>

在多線程的C++ 0x部分6:延遲初始化和雙重檢查與原子能

在多線程C +鎖定+ 0X部分7:鎖定多個互斥鎖,而不死鎖

在多線程的C++ 0x第8部分:期貨,承諾和異步函數調用

相關問題