小知识:linux下的C\C++多进程多线程编程实例详解

linux下的C\C++多进程多线程编程实例详解

1、多进程编程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
/* 创建一个子进程 */
child_pid = fork();
if(child_pid == 0)
{
printf(“child pid\n”);
exit(0);
}
else
{
printf(“father pid\n”);
sleep(60);
}
return 0;
}

 2、多线程编程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#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)、互斥

?
1
2
3
4
5
6
7
8
9
10
11
12
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)、条件变量

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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);
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/nyist327/article/details/44958585

声明: 猿站网有关资源均来自网络搜集与网友提供,任何涉及商业盈利目的的均不得使用,否则产生的一切后果将由您自己承担! 本平台资源仅供个人学习交流、测试使用 所有内容请在下载后24小时内删除,制止非法恶意传播,不对任何下载或转载者造成的危害负任何法律责任!也请大家支持、购置正版! 。本站一律禁止以任何方式发布或转载任何违法的相关信息访客发现请向站长举报,会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。本网站的资源部分来源于网络,如有侵权烦请发送邮件至:2697268773@qq.com进行处理。
建站知识

小知识:Linux 6 下编译安装 PHP 5.6实例详解

2023-4-3 6:30:04

建站知识

小知识:linux防火墙配置教程之允许转发实验(2)

2023-4-3 6:46:29

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索