[问题]ubuntu+c 多线程编程中一个关于花括号的奇怪问题......

软件和网站开发以及相关技术探讨
回复
头像
kahn
帖子: 9
注册时间: 2008-08-10 2:32

[问题]ubuntu+c 多线程编程中一个关于花括号的奇怪问题......

#1

帖子 kahn » 2008-08-17 6:34

代码: 全选

#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: :shock:
是pthread_*这类的函数返回有什么不同还是什么吗?
谁能帮忙解释一下,谢谢了。
头像
kahn
帖子: 9
注册时间: 2008-08-10 2:32

#2

帖子 kahn » 2008-08-19 4:18

顶一下······
tiankunmin
帖子: 38
注册时间: 2007-09-07 3:08

#3

帖子 tiankunmin » 2008-08-22 3:13

代码: 全选

 
      #define errexit(code,str) fprintf(stderr,"%s:%s\n",(str),strerror(code));exit(1); 
      if(errcode=pthread_create(&threads[worker],NULL,hola,&threads[worker])) 
      { 
         errexit(errcode,"pthread create"); 
      } 

宏会被替换为:

代码: 全选


     if(errcode=pthread_create(&threads[worker],NULL,hola,&threads[worker])) 
     { 
        fprintf(stderr,"%s:%s\n",(str),strerror(code));
        exit(1); 
     }
没加花括号就是:

代码: 全选

     if(errcode=pthread_create(&threads[worker],NULL,hola,&threads[worker])) 
        fprintf(stderr,"%s:%s\n",(str),strerror(code));
    exit(1); //总是被执行!
我也因为这个问题郁闷了一段时间,后来才发现的。
应当这样写:

代码: 全选

#define errexit(code,str) {fprintf(stderr,"%s:%s\n",(str),strerror(code));exit(1); }
头像
kahn
帖子: 9
注册时间: 2008-08-10 2:32

#4

帖子 kahn » 2008-08-30 12:21

哦````````明白了```谢谢``` :D
回复