• 【线程】linux之thread错误解决方案


     

    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...
    ");
        ret = pthread_join(new_thread, &thread_result);
        if (ret != 0)
        {
            perror("Thread Join Failed!");
            exit(EXIT_FAILURE);
        }
        printf("Thread Joined,returned:%s
    ", (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

  • 相关阅读:
    用户控件赋值
    计算一串数字中每个数字出现的次数
    如何理解c和c++的复杂类型声明
    STM32 NVIC学习
    stm32f10x_flash.c中文版
    IBM中国研究院Offer之感言——能力是一种态度
    对于STM32别名区的理解 (转载)
    STM32时钟学习之STM3210X_RCC.H解读
    STM32 DMA
    STM32 内部时钟输出PA.8(MCO)
  • 原文地址:https://www.cnblogs.com/lcw/p/3159516.html
Copyright © 2020-2023  润新知