多进程和多线程编程
来源:互联网 发布:python 入门书籍 编辑:程序博客网 时间:2024/05/21 08:37
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);
- }
- 多进程和多线程编程
- 多进程和多线程编程
- 多进程和多线程编程
- Python多线程和多进程编程
- 多线程编程和进程知识
- linux下多进程和多线程编程之一(使用)
- linux下多进程和多线程编程之二(同步)
- 多线程和多进程编程的背景知识
- python的多线程和多进程网络编程
- 高性能服务器编程--多进程和多线程
- 多进程和多线程
- 多线程和多进程
- 多进程和多线程
- 多进程和多线程
- 多线程和多进程
- 多进程和多线程
- 多进程和多线程
- 多进程和多线程
- linux中的延迟函数
- 岁月蹉跎,人生几何。
- 合成(Composite)模式
- Linux下的多线程编程
- ASCII表的简要记法
- 多进程和多线程编程
- css小知识
- 2012百度暑期实习_空间复杂度为O(1)的排序算法的实现(java)
- 介绍一下神器mimikatz,从lsass里抓密码
- PL/SQL 集合的方法
- [Python] 如何证明两组样本有显著性差异(t-test假设检验)
- 磁盘镜像配置DRBD配置
- ping百度的时候出现ping www.a.shifen.com
- 当我看到这个,我放弃安装小蓝鱼了