【问题标题】:C pthread written correctly but does not work at all; why?C pthread 编写正确,但根本不工作;为什么?
【发布时间】:2021-07-09 09:56:31
【问题描述】:

我正在为考试学习 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;
}

【问题讨论】:

  • argv[0] 是您的程序的名称。
  • 你也在做 create0/join0、create1/join1 等,但我认为教授希望你在等待之前先创建所有这些。
  • 投票结束,因为在调试方面没有任何努力。
  • 小贴士:使用strtol 而不是atoi。它可以让您发现错误。
  • char *ret; strcpy(ret,"Fine thread"); 这不起作用,因为ret 未初始化。这可能是段错误的原因。

标签: c ubuntu pthreads


【解决方案1】:

感谢一些开发者在第一个评论部分的贡献,我找到了解决练习的正确代码;在瘾中,我添加了一些代码来显示整数,而不是程序使用的内存位置。
代码如下:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-21
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多