2010-11-05 38 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部分:期货,承诺和异步函数调用

相关问题