代码: 全选
#ifdef __Linux__
#define _REENTRANT
#define _POSIX_SOURCE
#endif
#ifdef __Linux__
#define _P __P
#endif
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define NTHREADS 4
#define errexit(code,str) fprintf(stderr,"%s:%s\n",(str),strerror(code));exit(1);
void *hola(void *arg)
{
int myid=*(int *)arg;
printf("Hello,world,I'm%d\n",myid);
return arg;
}
int main(int argc,char *argv[])
{
int worker;
int ids[NTHREADS];
int errcode;
int *status;
pthread_t threads[NTHREADS];
for(worker=0;worker<NTHREADS;worker++)
{
ids[worker]=worker;
/*
*如果去掉下面的花括号,程序就不能正常运行
*/
if(errcode=pthread_create(&threads[worker],NULL,hola,&threads[worker]))
{
errexit(errcode,"pthread create");
}
}
for(worker=0;worker<NTHREADS;worker++)
{
/*
*同样奇怪的是,不去掉下面的花括号会在程序最后显示:thread (null) terminated abnormally
*/
if(errcode=pthread_join(threads[worker],(void *)&status))
{
errexit(errcode,"pthread join");
}
if(*status!=worker)
{
fprintf(stderr,"thread %s terminated abnormally\n",worker);
exit(1);
}
}
return 0;
}
去掉pthread_create的花括号(不管pthread_join加不加花括号):
kahn@kahn-PC:~/c$ ./pthread_hellow
kahn@kahn-PC:~/c$
只去掉pthread_join的花括号:
kahn@kahn-PC:~/c$ ./pthread_hellow
Hello,world,I'm-1210295408
Hello,world,I'm-1218688112
Hello,world,I'm-1227080816
kahn@kahn-PC:~/c$ ./pthread_hellow
Hello,world,I'm-1210168432
kahn@kahn-PC:~/c$
不去掉pthread_join的花括号:
kahn@kahn-PC:~/c$ ./pthread_hellow
Hello,world,I'm-1210029168
thread (null) terminated abnormally
kahn@kahn-PC:~/c$ ./pthread_hellow
Hello,world,I'm-1209943152
Hello,world,I'm-1218335856
Hello,world,I'm-1226728560
thread (null) terminated abnormally
kahn@kahn-PC:~/c$
只有一句语句的话,if加不加花括号都是一样的啊,但为什么……:shock:
是pthread_*这类的函数返回有什么不同还是什么吗?
谁能帮忙解释一下,谢谢了。