[英]How to spawn n threads?
我正在嘗試編寫一個多線程程序,基於命令行輸入的線程數,所以我不能硬編碼預先聲明的線程。 這是一種有效的方法嗎?
int threads = 5; // (dynamic, not hard-coded)
int i = 0;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
pthread_t foobar;
thread[i] = foobar; // will this cause a conflict?
}
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, (void *)&foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
以下是我在下面建議的修改結果。 似乎工作得很好。
int threads = 5;
int i;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
int ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
// pthread_join(thread[i], NULL); // don't actually want this here :)
}
sleep(1); // main() will probably finish before your threads do,
free(thread); // so we'll sleep for illustrative purposes
第一個周期是什么? 它是否將數組元素設置為未初始化的值?
所以我認為這就是你需要的:
int threads = 5, i = 0, ret = -1;
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (i = 0; i < threads; i++) {
ret = pthread_create(&thread[i], NULL, &foobar_function, NULL);
if(ret != 0) {
printf ("Create pthread error!\n");
exit (1);
}
}
它產生線程線程,在每個線程中啟動foobar_function 。 你有(如果一切順利):)他們在線程數組中的ID。 例如,您可以通過調用pthread_cancel(thread[1])
等來取消第二個線程。
第一個for
循環是無效的C,我不確定你想要它做什么。 除了foobar_function
上的錯誤foobar_function
外,只需將其刪除,其余代碼看起來就foobar_function
。 演職員應該是:
(void *(*)(void *))foobar_function
但除非類型已經是這個,或者非常接近,否則您的程序可能具有未定義的行為。 最好修復函數簽名,這樣就不需要強制轉換。
如果你想寫一個多線程程序,但不知道如何分配一個動態調整的數據結構,你可能會做錯事。
跑步之前學會走路。
考慮使用更簡單的語言,並避免使用(顯式)線程。
線程很難正確使用; 動態大小的數組很容易實現(在C中甚至相當容易)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.