zoukankan      html  css  js  c++  java
  • 【C】多线程编程笔记

    1. pthread_create(pthread类型指针变量 ,NULL ,函数 ,函数参数[多个参数用结构体传])

    2. pthread_join(pthread类型指针变量, 返回一般为null)

      pthread_join的作用:

         pthread_join()函数,以阻塞的方式等待thread指定的线程结束。

          如果不用这个函数,直接create后,进程也会运行,但是主线程不会等待这些子线程是否已经运行结束,而继续向下运行,很快主线程就结束了,而子线程还未运行完,被迫结束。

         加入pthread_join后,主线程会一直等待直到等待的线程结束自己才继续向下运行,使创建的线程有机会执行。

     1 #include <stdio.h>  
     2 #include <stdlib.h>
     3 #include <pthread.h>  
     4 #include <unistd.h>  
     5 #include <signal.h>
     6 
     7 typedef struct params{ 
     8         char * value;
     9         int num;
    10 }params;
    11 void thread_mess(params *);
    12 
    13 void main(void)
    14 {
    15 
    16         int err;
    17         pthread_t t1,t2;
    18         void *tret;
    19         
    20         params p_1={"threadd_1",1};     
    21         params p_2={"threadd_2",2};     
    22 
    23         err = pthread_create(&t1,NULL,(void *)thread_mess,&p_1);
    24         if(err != 0)
    25         {       
    26                 puts("error 1");
    27                 exit(1);
    28         }       
    29         err = pthread_create(&t2,NULL,(void *)thread_mess,&p_2);
    30         if(err != 0)
    31         {       
    32                 puts("error 2");
    33                 exit(1);
    34         }       
    35         
    36         //pthread_join第二个参数是接受的是pthread_exit返回的数据
    37         err = pthread_join(t1,&tret);
    38         printf("t1 join %d
    ",(int)tret);
    39         err = pthread_join(t2,&tret);
    40         printf("t2 join %d
    ",(int)tret);
    41 }
    42 
    43 void thread_mess(params * array)
    44 {
    45         printf("%s
    ",array->value);
    46         pthread_exit((void *)array->num);
    47 
    48 }    
  • 相关阅读:
    ubuntu下安装maven
    159.Longest Substring with At Most Two Distinct Characters
    156.Binary Tree Upside Down
    155.Min Stack
    154.Find Minimum in Rotated Sorted Array II
    153.Find Minimum in Rotated Sorted Array
    152.Maximum Product Subarray
    151.Reverse Words in a String
    150.Evaluate Reverse Polish Notation
    149.Max Points on a Line
  • 原文地址:https://www.cnblogs.com/hanyouchun/p/4401802.html
Copyright © 2011-2022 走看看