• 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;
    }
  • 相关阅读:
    ASCII码对照表 And HTML字符实体
    操作系统自带命令查看文件的哈希
    HMAC简介及HMAC-SHA256实现Demo
    CSV文件注入漏洞简析
    Kubernetes集群的安全机制
    Kubernetes -- Horizontal Pod Autoscaler
    获取两坐标之间距离
    在CentOS 7中搭建Git服务器
    centos7 搭建svn服务器
    node.js依赖express解析post请求四种数据格式()
  • 原文地址:https://www.cnblogs.com/dpf-learn/p/7561364.html
Copyright © 2020-2023  润新知