簡體   English   中英

按執行順序創建pthread

[英]Create pthread in order of execution

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

這里所有線程都是相互獨立的。 我不需要加入或同步它們。

在我的應用程序中,代碼在非常快的時間內執行3到4次,並且線程以隨機順序執行。

這是正常的行為,一旦創建了一個線程,它就會留給操作系統,下一次調度它的順序。

我想按照創建的順序執行線程執行。

您可以使用在所有線程中使用的計數信號量,讓它們等待特定的計數器值。

我更習慣於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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM