如何解决C pthread 编写正确但根本不起作用;为什么?
我正在 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;
}
有什么建议吗?我是不是搞砸了什么?
解决方法
感谢第一评论部分部分开发者的贡献,我找到了解决练习的正确代码;最后,我添加了一些代码来显示整数,而不是程序使用的内存位置。
代码如下:
#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],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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。