zoukankan      html  css  js  c++  java
  • pthread_create用法

    #include <pthread.h>

    int pthread_create(pthread_t *restrict tidp,
    const pthread_attr_t *restrict attr,
    void *(*start_rtn)(void), 
    void *restrict arg);

    Returns: 0 if OK, error number on failure

    一个参数为指向线程标识符的指针。

    第二个参数用来设置线程属性。
    第三个参数是线程运行函数的起始地址。
    最后一个参数是运行函数的参数。
     
    ps:
     

       编译的时候,一定要加上-lpthread选项,不然会报错:undefined reference to `pthread_create'。

      下面来看看pthread_create的声明:

      #include<pthread.h>

      int pthread_create(pthread_t *thread, pthread_addr_t *arr,

               void* (*start_routine)(void *), void *arg);

     

    •  thread   :用于返回创建的线程的ID
    • arr       : 用于指定的被创建的线程的属性,上面的函数中使用NULL,表示使用默认的属性
    • start_routine   : 这是一个函数指针,指向线程被创建后要调用的函数
    • arg      : 用于给线程传递参数,在本例中没有传递参数,所以使用了NULL

     

     

    简单的线程程序

     

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <unistd.h>
     
    #define    NUM_THREADS     8
     
    void *PrintHello(void *args)
    {
        int thread_arg;
        sleep(1);
        thread_arg = (int)args;
        printf("Hello from thread %d ", thread_arg);
        return NULL;
    }
     
    int main(void)
    {
        int rc,t;
        pthread_t thread[NUM_THREADS];
     
        for( t = 0; t < NUM_THREADS; t++)
        {
            printf("Creating thread %d ", t);
            rc = pthread_create(&thread[t], NULL, PrintHello, (void *)t);
            if (rc)
            {
                printf("ERROR; return code is %d ", rc);
                return EXIT_FAILURE;
            }
        }
        for( t = 0; t < NUM_THREADS; t++)
            pthread_join(thread[t], NULL);
        return EXIT_SUCCESS;
    }
  • 相关阅读:
    UVALive 5066 Fire Drill --BFS+DP
    Codeforces 486E LIS of Sequence --树状数组求LIS
    Codeforces 460D Little Victor and Set --分类讨论+构造
    Codeforces Round #285 (Div.1 B & Div.2 D) Misha and Permutations Summation --二分+树状数组
    计算机组成原理知识总结
    HDU 5155 Harry And Magic Box --DP
    【Python数据分析】简单爬虫 爬取知乎神回复
    《查拉图斯特拉如是说》读书笔记
    POJ 3384 Feng Shui --直线切平面
    POJ 2540 Hotter Colder --半平面交
  • 原文地址:https://www.cnblogs.com/dpf-learn/p/7561364.html
Copyright © 2011-2022 走看看