2016-12-27 32 views
1

我正在使用C++和pthread进行多线程。我想按创建Call的顺序执行线程。按执行顺序创建pthread

retrnThread=pthread_create(&thread_id,NULL,&HandleNotifications,(void*)Status); 

在我的应用程序中,上面的代码在非常快的时间执行3到4次,线程以随机顺序执行。我想按照创建的顺序执行线程执行。

retrnThread=pthread_create(&thread_id,NULL,&HandleNotifications1,(void*)Status); 
retrnThread=pthread_create(&thread_id,NULL,&HandleNotifications2,(void*)Status); 
retrnThread=pthread_create(&thread_id,NULL,&HandleNotifications3,(void*)Status); 
retrnThread=pthread_create(&thread_id,NULL,&HandleNotifications4,(void*)Status); 

执行顺序应该是: HandleNotifications1 HandleNotifications2 HandleNotifications3 HandleNotifications4

这里所有的线程是相互独立的。我不需要加入或同步它们。

+2

_“我不需要加入或同步它们。”_如果你想以特定的顺序执行线程,你必须。 –

+2

如果不能同时运行,创建4个线程有什么意义?只需创建一个按顺序处理通知的线程(如果您需要线程)。 – Mat

回答

0

在我的应用程序中,上面的代码在非常快的时间内执行3到4次,并且线程以随机顺序执行。

这是正常的行为,一旦线程被创建,它就留给操作系统,下一次按它的顺序排列。

我想按照创建的顺序执行线程。

您可以使用在所有线程中使用的计数信号量,并让它们等待特定的计数器值。

0

我更习惯了C#异步/等待/任务<>基于任务的异步模式(TAP)和我还需要了解,如果/ C++如何可以实现同样的功能

我们可以想象这样的事情(想象中的“主要”功能是由另一个外螺纹推出)

#include <iostream> 
#include <future> 

using namespace std; 

void handlenotification(int i = -1) 
{ 
    cout << "Task number " << i << endl; 
    //Long treatment here 
} 

int main() 
{ 
    cout << "Hello world!" << endl; 
    for (int i=0;i<4;i++) 
    { 
     async(launch::async,handlenotification,i); 
    } 

    cout << "Bye!" << endl; 
    return 0; 
} 

结果(无交错字符串)

Hello world! 
Task number 0 
Task number 1 
Task number 2 
Task number 3 
Bye! 

但它确实不要将控制权归还给调用线程(Bye!在最后)

我们将不得不构建更多的comp licated(通过推迟异步调用这个时候)来实现这一

#include <iostream> 
#include <future> 
#include <thread> 
#include <chrono> 
#include <list> 

using namespace std; 
using namespace chrono; 

list<future<void>> task_list; 

void handlenotification(int i = -1) 
{ 
    //standard output thread safety omitted for example !! 
    cout << "Task number " << i << endl ; 
    this_thread::sleep_for(seconds(i)); 
} 

void naive_background_worker(void) 
{ 
    while(true) 
    { 
     //Thread safety omitted for example !! 
     if (!task_list.empty()) 
     { 
      task_list.front().wait(); 
      task_list.pop_front(); 
     } 
     else 
     { 
      //naive 
      this_thread::sleep_for(milliseconds(50)); 
     } 
    } 

} 

int main() 
{ 
    //standard output thread safety omitted for example !! 
    cout << "Hello world!" << endl; 
    for (int i=1;i<=4;i++) 
    { 
     //Thread safety for list omitted for example !! 
     task_list.push_back(async(launch::deferred,handlenotification,i)); 
    } 

    thread back_worker = thread(naive_background_worker); 


    cout << "Bye!" << endl; 

    back_worker.join(); 

    return 0; 
} 

结果是(为COUT这里没有线程安全! +永不结束后台工作者)

Hello world! 
Bye!Task number 
1 
Task number 2 
Task number 3 
Task number 4