-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpthread_test.cpp
More file actions
90 lines (85 loc) · 2.12 KB
/
pthread_test.cpp
File metadata and controls
90 lines (85 loc) · 2.12 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* @brief: pthread api 基本使用:单生产者-多消费者
*/
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <queue>
#include <time.h>
#define LOG(format, ...)\
do{\
char str[26]={0};\
time_t now =time(NULL);\
tm*time_info = localtime(&now);\
strftime(str,sizeof(str),"%Y-%m-%D %H:%M:S",time_info);\
printf("[%s] [%d] " format "\n",str,pthread_self(),##__VA_ARGS__);\
}while(0)
// 全局变量
std::queue<int> que;
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
std::vector<pthread_t> threads;
bool consume_thread_if_exit = false;
// 生产者线程函数
void* produce_thread_func(void* arg)
{
LOG("produce thread start!");
int* p = (int*)arg;
if (*p <= 0)
{
consume_thread_if_exit = true;
return NULL;
}
for (int i = 0; i < *p; i++)
{
usleep(100);
pthread_mutex_lock(&count_mutex);
LOG("produce %d", i+1);
que.push(i + 1);
pthread_mutex_unlock(&count_mutex);
}
consume_thread_if_exit = true;
return NULL;
}
// 消费者线程函数
void* consume_thread_func(void* arg)
{
LOG("consume thread start!");
while (!consume_thread_if_exit)
{
pthread_mutex_lock(&count_mutex);
if (!que.empty())
{
LOG("consume %d", que.front());
que.pop();
}
pthread_mutex_unlock(&count_mutex);
}
return NULL;
}
void create_threads()
{
// 创建生产者
pthread_t produce_thread_id = 0;
int produce_count = 100;
pthread_create(&produce_thread_id,NULL, produce_thread_func, (void*)&produce_count);
threads.push_back(produce_thread_id);
// 创建三个消费者
for (int i = 0; i < 3; i++)
{
pthread_t consume_thread_id = 0;
pthread_create(&consume_thread_id,NULL, consume_thread_func,NULL);
pthread_join(consume_thread_id, NULL);
}
}
int main(int argc, char** argv)
{
LOG("start!");
// 初始化互斥锁
pthread_mutex_init(&count_mutex,NULL);
create_threads();
LOG("release the mutex!");
//释放资源
pthread_mutex_destroy(&count_mutex);
return 0;
}