An issue of errno in a multi-threaded environment under AIX

A problem about errno in a multi-threaded environment under AIX was reported in our product in these days.


The program works well before the introduction of a lower-level component which is mutil-threaded. But now it always exits during the startup process. After debugging we located the problem. The program calls function mkdir during startup to create directory and then take corresponding actions according to the return value of mkdir and the value errno. If the return value is -1 and errno is EEXIST, the program thinks the directory already exsits. But actually the return value is -1 and errno is not EEXIST but 0 when the directory exists, so the program exits because it thinks the directory can not be created.


The problem occurs just when the multi-threaded component is refered, therefore we can easily have clue to check where the problem is.

 

The definition of errno in errno.h is like the following:

 

#if defined(_THREAD_SAFE) || defined(_THREAD_SAFE_ERRNO)
/*
 * Per thread errno is provided by the threads provider. Both the extern int
 * and the per thread value must be maintained by the threads library.
 */
extern  int     *_Errno( void );
#define errno   (*_Errno())

#else

extern int errno;

#endif  /* _THREAD_SAFE || _THREAD_SAFE_ERRNO */

 

That is to say, errno can be used in multi-threaded environment if either THREAD_SAFE or _THREAD_SAFE_ERRNO is defined. The errno is not an integer but a functional pointer in such case.

 

But it is still confused because many modules are working well although THREAD_SAFE and  _THREAD_SAFE_ERRNO are both not explicitly defined.

 

I remembered the pthread.h should be the first included header file in multi-threaded programming because the first code segment in pthread.h is just to define _THREAD_SAFE:

#ifndef _THREAD_SAFE
#define _THREAD_SAFE      1
#endif

  

 

Unfortunately many software engineers don't pay attention to this issue so that pthread.h is not at the first place in many source files. And it is too difficult for us to modify all files. Our solution is to add -D_THREAD_SAFE in makefile.

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章