pthread

    技术2022-05-19  18

    下午调试程序的“segmentation fault”,先上代码:

    int main() { printf("entering main() /n"); init_globals(); /*initialize global variable defined in main.c*/ init_iic(); init_spi(); if(init_sock() == -1){ exit(1); } sock_listen_tid = pthread_create(&sock_listen_tid,NULL,listen_thread,NULL); if( sock_listen_tid!= 0){ printf("pthread_create() error /n"); exit(1); } //sleep(10); pthread_join(sock_listen_tid,NULL); return 0; } void* listen_thread(void* arg) { //省略 return ((void*)0); } 

     

    左看右看找不到错在那,尝试去掉pthread_join, 竟然正常了。

     

    注意这句:

    sock_listen_tid = pthread_create(&sock_listen_tid,NULL,listen_thread,NULL);

     

    pthread_create的返回值赋给了sock_listen_tid,这行代码看起来的确的确的确有些怪~

     

    看函数说明 man 3 pthread_create

     

    函数返回值描述如下:

     

    RETURN VALUE

           If successful, the pthread_create() function shall return  zero;  otherwise,

           an error number shall be returned to indicate the error.

    ERRORS

           The pthread_create() function shall fail if:

           EAGAIN The  system  lacked the necessary resources to create another thread,

                  or the system-imposed limit on the  total  number  of  threads  in  a

                  process {PTHREAD_THREADS_MAX} would be exceeded.

           EINVAL The value specified by attr is invalid.

           EPERM  The  caller  does not have appropriate permission to set the required

                  scheduling parameters or scheduling policy.

           The pthread_create() function shall not return an error code of [EINTR].

           The following sections are informative.

     

     

    如果创建成功, pthread_create将返回0. 赋值给sock_listen_tid等于0。然后执行pthread_join(0, NULL),相当于等待线程号为0的线程,当然segmentation fault

     

     


    最新回复(0)