zoukankan      html  css  js  c++  java
  • 【线程】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

  • 相关阅读:
    jquery图片播放弹出插件Fancybox
    D3js-API介绍【英】
    ZOJ 3156 Taxi (二分匹配+二分查找)
    linux权限之su和sudo的差别
    CareerCup之1.6 Rotate Image
    [oracle]pl/sql --分页过程demo
    已迁移到http://www.coffin5257.com
    C# 之 集合ArrayList
    Java 序列化Serializable具体解释(附具体样例)
    Android 短信验证码控件
  • 原文地址:https://www.cnblogs.com/lcw/p/3159516.html
Copyright © 2011-2022 走看看