按执行顺序创建Pthread



我正在使用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); 

执行订单应为:处理1Handlenotification2Handlenotification3Handlenotification4

这里所有线程彼此独立。我不需要加入或同步它们。

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

这是正常行为,一旦创建线程,它就会剩下下次安排的顺序。

我想以与创建相同的顺序进行线程执行。

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

我更习惯于c#async/等待/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

最新更新