C pthread编写正确,但根本不工作;为什么?

C pthread编写正确,但根本不工作;为什么?,c,ubuntu,pthreads,C,Ubuntu,Pthreads,我正在为考试学习c语言的线程,我正在尝试解决教授作为培训给出的以下练习: 编写一个程序,从命令行接受整数“n”,并创建n个线程;然后等待它们的终止。 我试图解决这个问题,但由于某种原因,它似乎不起作用。 这是我的代码: #include <pthread.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> void *Stam

我正在为考试学习c语言的线程,我正在尝试解决教授作为培训给出的以下练习:

编写一个程序,从命令行接受整数“n”,并创建n个线程;然后等待它们的终止。


我试图解决这个问题,但由于某种原因,它似乎不起作用。
这是我的代码:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void *StampaThread(void *arg){
   char *ret;
   strcpy(ret,"Fine thread");
   printf("thread %p scritto!\n", arg);
   pthread_exits(ret);
}

int main(int argc,char** argv){

pthread_t thread[1000];
void *ret;

if(argc!=2){
   perror("Argomenti insufficienti o in eccesso!\n");
}
else
{
   int n=atoi(argv[0]);
   int i;
   for(i=0;i<n;i++){
      if(pthread_create(&thread[i],NULL,StampaThread,&i)!=0){
         perror("problema nella creazione dei thread\n");
         exit(1);
      }
      if((pthread_join(thread[i],&ret))!=0){
         perror("problema nella attesa dei thread\n");
         exit(3);
      }
      printf("%s",(char *)ret);
   }
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
void*StampaThread(void*arg){
char*ret;
strcpy(ret,细螺纹);
printf(“线程%p scritto!\n”,arg);
pthread_退出(ret);
}
int main(int argc,字符**argv){
pthread_t线程[1000];
void*ret;
如果(argc!=2){
perror(“在eccesso中Argomenti不足!\n”);
}
其他的
{
int n=atoi(argv[0]);
int i;

对于(i=0;i多亏了一些开发人员在第一个注释部分所做的贡献,我找到了解决该练习的正确代码;在addiction中,我添加了一些代码来显示过程使用的整数,而不是内存位置。
代码如下:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void *StampaThread(void *arg){
   char *ret=(char *)malloc(sizeof(char *));
   strcpy(ret,"Fine thread");
   printf("thread %d scritto!\n", *(int *)arg);
   free(arg);
   pthread_exits(ret);
}

int main(int argc,char** argv){

pthread_t thread[1000];
void *ret;

if(argc!=2){
   perror("Argomenti insufficienti o in eccesso!\n");
}
else
{
   int n=strtol(argv[1],NULL,10);
   int i;
   int *arg;
   for(i=0;i<n;i++){
      arg=malloc(sizeof(*arg));
      *arg=i;
      if(pthread_create(&thread[i],NULL,StampaThread,arg)!=0){
         perror("problema nella creazione dei thread\n");
         exit(1);
      }
   }
   for(i=0;i<n;i++){
      if((pthread_join(thread[i],&ret))!=0){
         perror("problema nella attesa dei thread!\n");
         exit(3);
      }
    }
    printf("%s",(char *)ret);
}
return 0;
}
#包括
#包括
#包括
#包括
#包括
void*StampaThread(void*arg){
char*ret=(char*)malloc(sizeof(char*));
strcpy(ret,细螺纹);
printf(“线程%d scritto!\n”,*(int*)arg);
自由(arg);
pthread_退出(ret);
}
int main(int argc,字符**argv){
pthread_t线程[1000];
void*ret;
如果(argc!=2){
perror(“在eccesso中Argomenti不足!\n”);
}
其他的
{
int n=strtol(argv[1],NULL,10);
int i;
int*arg;

for(i=0;iargv[0]是您程序的名称。您也在执行create0/join0、create1/join1等操作,但我认为教授希望您在等待之前先创建所有这些操作。投票关闭,因为在调试过程中没有任何努力。附带提示:使用
strtol
而不是
atoi
。它允许您发现错误。
char*ret;strcpy(ret),“细螺纹”);
ret
未初始化时无法工作。这可能是seg故障的原因。