【Linux技术】linux之thread错误解决方案

来源:互联网 发布:算法设计与分析怎么学 编辑:程序博客网 时间:2024/06/05 00:23

1.错误现象:


undefined reference to 'pthread_create'undefined reference to 'pthread_join'




2.问题原因:


   pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用    pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。



3.问题解决:


在编译中要加 -lpthread参数

gcc thread.c -o thread -lpthread
   thread.c为你些的源文件,不要忘了加上头文件#include<pthread.h>


4.源码:
//thread_currentTime.c#include <stdio.h>#include <stdlib.h>#include <time.h>#include <unistd.h>#include <pthread.h>void *Print_CurrentTime(void);int main (){    int ret;    void *thread_result;    pthread_t new_thread;    ret = pthread_create(&new_thread,NULL,Print_CurrentTime,NULL);    if (ret != 0)    {        perror("Thread Creation Failed!");        exit(EXIT_FAILURE);    }    printf("Waiting for New thread...\n");    ret = pthread_join(new_thread, &thread_result);    if (ret != 0)    {        perror("Thread Join Failed!");        exit(EXIT_FAILURE);    }    printf("Thread Joined,returned:%s\n", (char *)thread_result);    return 0;}void *Print_CurrentTime(void){    time_t lt;    lt =time(NULL);     printf ("Current Time: %s",ctime(&lt));      pthread_exit("New Thread Finished!");}


5.mystery注解


   1)默认状态下创建的线程是非分离状态的线程(线程的分离属性指明一个线程以什么样的方式来终止自己

   2)非分离状态的线程必须调用pthread_join()函数等待创建的线程结束,当函数pthread_join()返回时,新创建的线程才终止并释放自己占有的资源。
   3)分离状态的线程不需要原线程等待,函数运行结束线程便终止,同时释放占用的资源


本文出自 “成鹏致远” 博客,请务必保留此出处http://infohacker.blog.51cto.com/6751239/1155041

原创粉丝点击