按执行顺序创建pthread

时间:2016-12-27 15:17:05

标签: c++ multithreading pthreads

我正在使用C ++和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 个答案:

答案 0 :(得分:0)

  

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

这是正常的行为,一旦创建了一个线程,它就会留给操作系统,而下一次它将按顺序安排。

  

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

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

答案 1 :(得分:0)

我更习惯于C#async / await / Task<>基于任务的异步模式(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!就在最后)

我们必须构建一些更复杂的东西来实现这个目标(这次推迟异步调用

#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
相关问题