-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpthread_det.cpp
58 lines (47 loc) · 1.13 KB
/
pthread_det.cpp
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
#include <iostream>
#include <chrono>
#include <unistd.h>
#include <pthread.h>
void *thread_func(void *thread_contx)
{
while (1) {
sleep(1);
std::cout <<" thread " << pthread_self() << std::endl;
}
}
int main()
{
pthread_attr_t attr;
pthread_t thread_id;
int ret;
ret = pthread_attr_init(&attr);
if (ret < 0) {
return -1;
}
ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (ret < 0) {
return -1;
}
ret = pthread_create(&thread_id, &attr, thread_func, &thread_id);
if (ret < 0) {
return -1;
}
int detach_state = 0;
ret = pthread_attr_getdetachstate(&attr, &detach_state);
if (ret < 0) {
return -1;
}
if (detach_state == PTHREAD_CREATE_DETACHED) {
std::cout << "thread created as detached..\n" ;
} else if (detach_state == PTHREAD_CREATE_JOINABLE) {
std::cout << "thread created as joniable\n";
}
if (detach_state == PTHREAD_CREATE_JOINABLE) {
pthread_join(thread_id, NULL);
} else {
while (1) {
sleep(1);
}
}
return 0;
}