學習pthreads,但我無法創建它們。這裏是我的輸出和GDB信息:難度創建Pthreads(錯誤22)
In main(), creating thread 1 ERROR: return code from pthread_create() is 22 for thread 1 In main(), creating thread 2 ERROR: return code from pthread_create() is 22 for thread 2 In main(), creating thread 3 ERROR: return code from pthread_create() is 22 for thread 3 In main(), creating thread 4 ERROR: return code from pthread_create() is 22 for thread 4 In main(), creating thread 5 ERROR: return code from pthread_create() is 22 for thread 5 Program received signal SIGSEGV, Segmentation fault. 0xb7fb4d8a in pthread_join (threadid=76038327, thread_return=0x0) at pthread_join.c:46 46 pthread_join.c: No such file or directory.
這裏是我的代碼:
#include <stdlib.h>
#include <stdio.h>
#include <strings.h>
#include <errno.h>
#include <pthread.h>
#include <unistd.h>
#define SBUFSIZE 1025
char errorstr[SBUFSIZE];
FILE* inputfp[5];
void* f(void* inpFile) {
fprintf(stderr, "%s\n", (char*)inpFile);
return NULL;
}
int main (int argc, char* argv[]) {
int i;
/* Thread Variables */
pthread_attr_t attr;
pthread_t *th[argc-2]; //one thread for each input file
/* allocate memory for the threads */
for (i = 0; i < (argc-2); i++) {
th[i] = (pthread_t *) malloc(sizeof(pthread_t));
inputfp[i] = fopen(argv[i], "r");
if (!inputfp[i]) {
sprintf(errorstr, "Error Opening Input File: %s", argv[i]);
perror(errorstr);
}
}
/* Create one thread for each input file */
for (i = 1; i < (argc - 1); i++) {
fprintf (stderr, "In main(), creating thread %1d\n", i);
int rc = pthread_create (th[i], &attr, f, inputfp[i-1]);
if (rc) {
printf("ERROR: return code from pthread_create() is %d for thread %d\n",
rc, i);
}
}
/* wait for the threads to finish */
for (i = 1; i < (argc - 1); i++) {
pthread_join(*th[i], 0);
}
return EXIT_SUCCESS;
}
我失去了一些東西,但我不知道是什麼。誰能幫忙?謝謝!
編輯:這裏是我如何更改從約阿希姆Pileborg每個建議的代碼。我仍然收到從pthread_create()返回的錯誤22,但pthread_join上的SIGSEGV錯誤不再發生。
任何人都有關於如何讓pthread_create()返回0(表示成功創建線程)的任何建議?再次感謝!
int main (int argc, char* argv[]) {
int i;
/* Thread Variables */
pthread_attr_t attr;
pthread_t *th[argc-2]; //one thread for each input file
/* allocate memory for the threads */
for (i = 0; i < (argc-2); i++) {
th[i] = (pthread_t *) malloc(sizeof(pthread_t));
printf("%s\n", argv[i+1]);
inputfp[i] = fopen(argv[i+1], "r");
if (!inputfp[i]) {
sprintf(errorstr, "Error Opening Input File: %s", argv[i]);
perror(errorstr);
}
}
/* Create one thread for each input file */
for (i = 0; i < (argc - 2); i++) {
fprintf (stderr, "In main(), creating thread %1d\n", i);
int rc = pthread_create (th[i], &attr, f, inputfp[i]);
if (rc) {
printf("ERROR: return code from pthread_create() is %d for thread %d\n",
rc, i);
}
}
/* wait for the threads to finish */
for (i = 0; i < (argc - 2); i++) {
pthread_join(*th[i], 0);
}
return EXIT_SUCCESS;
}
這是很好的,你用GDB幫助調試,但是當你得到分段錯誤,你可以使用'bt'命令來顯示函數調用堆棧,並使用'up'來調用堆棧。使用'up'來達到你的代碼後,你可以'打印'變量來看看它們是否正常。 – 2013-02-23 05:04:35