我正在嘗試學習 C 中的多執行緒。我正在嘗試將向量的元素作為引數傳遞給 pthread_create。但是,它沒有按預期作業。
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <vector>
using namespace std;
void *count(void *arg)
{
int threadId = *((int *)arg);
cout << "Currently thread with id " << threadId << " is executing " << endl;
pthread_exit(NULL);
}
int main()
{
pthread_t thread1;
vector<int> threadId(2);
threadId[0] = 99;
threadId[1] = 100;
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]);
if (retVal)
{
cout << "Error in creating thread with Id: " << threadId[0] << endl;
exit(-1);
}
pthread_t thread2;
retVal = pthread_create(&thread2, NULL, count, (void *)&threadId[1]);
if (retVal)
{
cout << "Error in creating thread with Id: " << threadId[1] << endl;
exit(-1);
}
pthread_exit(NULL);
}
我得到的輸出是:
當前正在執行 id 為 99 的執行緒。
當前正在執行 id 為 0 的執行緒
但是,在我看來,它應該是:
當前正在執行 id 為 99 的執行緒。
當前正在執行 id 為 100 的執行緒。
我在這里想念什么?
uj5u.com熱心網友回復:
int retVal = pthread_create(&thread1, NULL, count, (void *)&threadId[0]);
無論如何,您無法保證新的執行執行緒現在正在運行,就在這一刻,沒有任何延遲。
唯一pthread_create能保證你的是執行緒函式 ,thread1將在某個時候開始執行。它可能在pthread_create()它自己回傳之前。或者它可能在之后的某個時候。新執行緒函式何時開始執行確實是一個很大的謎,但你可以把它帶到銀行,新的執行執行緒將開始。最終。
您的第二個執行執行緒也是如此。
因此,兩個執行執行緒都可以在您回傳后main()以及在您的向量被破壞后很好地啟動。顯示的代碼中沒有任何內容可以保證執行執行緒將在向量(其內容以所示方式傳遞給它們)被破壞之前執行。這會導致未定義的行為。
您將需要使用必須使用的其他與執行緒相關的工具,以便正確同步多個執行執行緒。此外,您使用的是較舊的 POSIX 執行緒。現代 C 使用std::thread的 s 提供了許多優于其前身的優點,是完全型別安全的(沒有丑陋的強制轉換)并且具有許多防止常見編程錯誤的屬性(但是,在這種情況下std::threads 也沒有同步保證,這通常是這種情況所有典型的執行執行緒實作)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496631.html
上一篇:javaExecutorService.awaitTermination()是否阻塞主執行緒并等待?
下一篇:任務相互等待完成
