簡體   English   中英

線程分割錯誤

[英]segmentation fault from threads

我已經在下面編寫了代碼,但是當我運行它時會帶來分段錯誤。 雖然它可以正確編譯。 我的錯誤在哪里?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
  int *i = (int *) arg;
  char buf[123];
  snprintf(buf, sizeof(buf), "thread %d", *i);
  return buf;
}

int main(int argc, char *argv[]) {
  int i;
  pthread_t *pt = NULL;
  for (i = 0; i < N; i++) {
    pthread_create(pt, NULL, run, &i);
  }
  return EXIT_SUCCESS;
}

任何提示都歡迎。

謝謝

您遇到服務器問題:

1)您正在將NULL傳遞給pthread_create() ,這可能是segfault的原因。

2)您不必等待線程完成(當main線程退出整個進程時死亡)。

3)您將地址相同的變量i傳遞給所有線程。 這是一場數據競賽

4)您正在從線程函數返回局部變量buf的地址。

您可以像這樣修復它:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
static int N = 5;
static void* run(void *arg) {
  int *i = (int *) arg;
  char *buf = malloc(16);
  snprintf(buf, 16, "thread %d", *i);
  return buf;
}

int main(int argc, char *argv[]) {
  int i;
  void *ret;
  int arr[N];
  pthread_t pt[N];

  for (i = 0; i < N; i++) {
    arr[i] = i;
    pthread_create(&pt[i], NULL, run, &arr[i]);
  }

  for (i = 0; i < N; i++) {
    pthread_join(pt[i], &ret);
    printf("Thread %d returned: %s\n", i, (char*)ret);
    free(ret);
  }
  return EXIT_SUCCESS;
}

請注意,您不需要使用pthread_join()調用。 您還可以從主線程中校准pthread_exit() ,以便僅主線程退出而其他線程繼續。

暫無
暫無

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

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