C++多进程和多线程编程的方法是什么

发布时间:2022-10-14 14:28:17 作者:iii
来源:亿速云 阅读:128

这篇文章主要介绍了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); 
}

关于“C++多进程和多线程编程的方法是什么”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“C++多进程和多线程编程的方法是什么”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 【C/C++】c++多进程与hiredis的浅使用
  2. Node.js中的多线程和多进程是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:c++如何实现string与time_t互相转换

下一篇:如何用C++实现Windows环境聊天室功能

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》