国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 服務器 > Linux服務器 > 正文

linux下的C/C++多進程多線程編程實例詳解

2024-09-05 23:03:49
字體:
來源:轉載
供稿:網友

linux下的C/C++多進程多線程編程實例詳解

1、多進程編程

#include <stdlib.h> #include <sys/types.h> #include <unistd.h>  int main() {   pid_t child_pid;    /* 創建一個子進程 */   child_pid = fork();   if(child_pid == 0)   {     printf("child pid/n");     exit(0);   }   else   {     printf("father pid/n");     sleep(60);   }      return 0; } 

 2、多線程編程

#include <stdio.h> #include <pthread.h>  struct char_print_params {   char character;   int count; };  void *char_print(void *parameters) {   struct char_print_params *p = (struct char_print_params *)parameters;   int i;    for(i = 0; i < p->count; i++)   {     fputc(p->character,stderr);   }    return NULL; }  int main() {   pthread_t thread1_id;   pthread_t thread2_id;   struct char_print_params thread1_args;   struct char_print_params thread2_args;    thread1_args.character = 'x';   thread1_args.count = 3000;   pthread_create(&thread1_id, NULL, &char_print, &thread1_args);    thread2_args.character = 'o';   thread2_args.count = 2000;   pthread_create(&thread2_id, NULL, &char_print, &thread2_args);    pthread_join(thread1_id, NULL);   pthread_join(thread2_id, NULL);    return 0; } 

 3、線程同步與互斥

1)、互斥

pthread_mutex_t mutex; pthread_mutex_init(&mutex, NULL);  /*也可以用下面的方式初始化*/ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  pthread_mutex_lock(&mutex); /* 互斥  */  thread_flag = value;  pthread_mutex_unlock(&mutex); 

2)、條件變量

int thread_flag = 0; pthread_mutex_t mutex; pthread_cond_t thread_flag_cv;/  void init_flag() {   pthread_mutex_init(&mutex, NULL);   pthread_cond_init(&thread_flag_cv, NULL);   thread_flag = 0; }  void *thread_function(void *thread_flag) {   while(1)   {     pthread_mutex_lock(&mutex);     while(thread_flag != 0 )     {       pthread_cond_wait(&thread_flag_cv, &mutex);     }     pthread_mutex_unlock(&mutex);      do_work();   }    return NULL; }  void set_thread_flag(int flag_value) {   pthread_mutex_lock(&mutex);   thread_flag = flag_value;    pthread_cond_signal(&thread_flag_cv);   pthread_mutex_unlock(&mutex); } 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 武穴市| 高台县| 上林县| 青河县| 循化| 类乌齐县| 宜章县| 黔东| 天津市| 察哈| 信丰县| 盐津县| 辽中县| 昭觉县| 潞城市| 青田县| 鸡西市| 湖州市| 肥东县| 育儿| 重庆市| 上思县| 高要市| 长春市| 合作市| 蒙阴县| 玉树县| 霍林郭勒市| 刚察县| 成都市| 平遥县| 来宾市| 淮阳县| 天祝| 新源县| 都兰县| 邵阳县| 信宜市| 石家庄市| 且末县| 高陵县|