这是我第一次使用线程,我从一个简单的程序开始。该程序接受n
参数并创建n-2
线程。问题是我遇到了分段错误,我不知道为什么。
这是代码:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
void *
removeBytes (int i, char* argv[])
{
printf ("%d, %s\n", i, argv[i]);
return NULL;
}
int main (int argc, char *argv[])
{
pthread_t threads[argc - 3];
int err;
int i;
int *ptr[argc - 3];
printf ("argc = %d\n", argc);
for (i = 0; i < argc -3; i++)
{
err =
pthread_create (&(threads[i]), NULL,
removeBytes(i+1,&argv[i+1]), NULL);
if (err != 0)
{
printf ("\nCan't create thread: [%d]", i);
}
else
{
printf ("\nThread created successfully\n");
}
}
for (i = 0; i < argc - 3; i++)
{
pthread_join (threads[i], (void **) &(ptr[i]));
printf("pthread_join - thread %d",i);
}
return 0;
}
示例:我的程序被调用mythread
,所以当我运行它时./mythread f1 f2 f3 f4 f5 f6
,输出是:
argc = 6
1,f2
Thread created successfully
2,f4
Thread created successfully
3, (null)
为什么需要f2
asargv[1]
和f4
as argv[2]
?
更新:
typedef struct{
int i;
char* argv;
}Data;
void* removeBytes(void* arg){
Data* data = (Data*)arg;
printf("%d, %s\n",data->i, data->argv);
free(data);
return NULL;
}
int main(int argc, char** argv){
Data* data;
pthread_t threads[argc-3];
int i;
int err;
for(i=0; i < argc-3;i++){
data = (Data*)malloc(sizeof(Data));
data->i=i+1;
data->argv=argv[i+1];
err = pthread_create(&(threads[i]),NULL,removeBytes,data);
if(err != 0){
printf("\nCan't create thread %d",i);
}
else{
printf("Thread created successfully\n");
}
}
return 0;
}
对于 ./mythread f1 f2 f3 f4 f5 f6 f7 f8 输出为:
5 x“线程创建成功”。它不打印 i 或 argvi[i]。