試圖通過運行一個簡單的程式來查看 pthread 是如何作業的,但我在 pthread_create 處遇到了分段錯誤(核心轉儲)
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void* testfunc(void* arg) {
while (1) {
printf("testfunc");
}
}
int main(void) {
printf("helo\n");
if (pthread_create(NULL, NULL, &testfunc, NULL) != 0) {
perror("pthread failed to create\n");
}
while (1) {
printf("main function\n");
sleep(1000);
}
return 0;
}
似乎是什么導致了問題?如果重要的話,我在 Ubuntu 20.04 上。
uj5u.com熱心網友回復:
你不能通過NULLforpthread_create的第一個引數。
在回傳之前,成功呼叫
pthread_create()將新執行緒的 ID 存盤在指向的緩沖區中thread
此外,pthread_create沒有設定errno,所以使用perror沒有意義,至少在沒有一些準備的情況下不會。
出錯時,它回傳一個錯誤號,其內容
*thread未定義。
固定的:
pthread_t thread;
if ( ( errno = pthread_create(&thread, NULL, &testfunc, NULL) ) != 0 ) {
perror("pthread failed to create\n");
}
...
pthread_join(thread, ...); // Normally.
uj5u.com熱心網友回復:
c 中的執行緒非常無情。我可以看到您的代碼存在一些問題。
首先,您可能需要參考p_thread. 他們有很好的記錄。您目前擁有的是一個執行緒呼叫,但您沒有指向該執行緒的任何內容。這就是您收到分段錯誤的原因。這意味著您的程式在嘗試呼叫它時在某處丟失了指向該執行緒的指標。我建議類似的東西。
pthread_t thread;
int * argument = 5;
if(pthread_create(&thread,NULL, &testfunc, &argument) !=0){
// ^This is a pointer to your argument
// that you want to pass in
perror("pthread failed to create\n");
exit(1);
}
并且您的執行緒函式還需要從 void 指標型別轉換為您希望它回傳使用的任何內容。然后它需要在從執行緒例程回傳之前被轉換回一個空指標。
void* testfunc(void* arg){
int* testVar = (int *)arg;
// do some logic here
return (void *) testVar;
}
最后,您要對 C 中的記憶體負責,因此您必須在退出之前終止您創建的執行緒。
pthread_join(thread, NULL);
我的第一個建議是您觀看一些與之相關的視頻。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370316.html
下一篇:程式未正確讀取“雙重”輸入
