• 多线程的创建、退出、等待、删除语法


    1、多线程创建pthread_create()的语法

        

    2、多线程退出pthread_exit()的语法

      

    3、多线程等待pthread_join()的语法

      

    4、多线程删除pthread_cancel()的语法

      

    代码分析:

    /* thread.c */
    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #define THREAD_NUMBER        3                /*线程数*/
    #define REPEAT_NUMBER        5                /*每个线程中的小任务数*/
    #define DELAY_TIME_LEVELS    10.0            /*小任务之间的最大时间间隔*/
    
    void *thrd_func(void *arg)
    { /* 线程函数例程 */
        int thrd_num = (int)arg;
        int delay_time = 0;
        int count = 0;
        
        printf("Thread %d is starting
    ", thrd_num);
        for (count = 0; count < REPEAT_NUMBER; count++)
        {
            delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;
            sleep(delay_time);
            printf("	Thread %d: job %d delay = %d
    ", thrd_num, count, delay_time);
        }
        printf("Thread %d finished
    ", thrd_num);
        pthread_exit(NULL);
    }
    int main(void)
    {
        pthread_t thread[THREAD_NUMBER];
        int no = 0, res;
        void * thrd_ret;
        
        srand(time(NULL));
        
        for (no = 0; no < THREAD_NUMBER; no++)
        {
            /* 创建多线程 */
            res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);
            if (res != 0)
            {
                printf("Create thread %d failed
    ", no);
                exit(res);
            }
        }
        printf("Create treads success
     Waiting for threads to finish...
    ");
        for (no = 0; no < THREAD_NUMBER; no++)
        {
            /* 等待线程结束 */
            res = pthread_join(thread[no], &thrd_ret);
            if (!res)
            {
                printf("Thread %d joined
    ", no);
            }
            else
            {
                printf("Thread %d join failed
    ", no);
            }
        }
        return 0;
    }
  • 相关阅读:
    公平锁和非公平锁
    读写锁StampedLock的思想
    线程工作窃取算法
    关于SQL注入的问题以及解决方法
    简单工厂模式、工厂模式和抽象工厂模式
    RestFul的无状态规则详解
    Identity Server 4 中文文档(v1.0.0) 目录
    第3章 支持和规范
    第2章 术语
    第1章 背景
  • 原文地址:https://www.cnblogs.com/yihujiu/p/5597448.html
Copyright © 2020-2023  润新知