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

  • 相关阅读:
    fail-fast以及Iterator对象
    LeetCode~1351.统计有序矩阵中的负数
    LeetCode~75.颜色分类
    LeetCode~5364. 按既定顺序创建目标数组
    LeetCode~945.使数组唯一的最小增量
    LeetCode~409. 最长回文串
    笔记: SpringBoot + VUE实现数据字典展示功能
    JSON parse error: Cannot deserialize value of type `java.util.Date` from String
    为什么要用location的hash来传递参数?
    初识Git
  • 原文地址:https://www.cnblogs.com/lcw/p/3159516.html
Copyright © 2011-2022 走看看