-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy pathposix_thread_02.cpp
More file actions
38 lines (28 loc) · 866 Bytes
/
posix_thread_02.cpp
File metadata and controls
38 lines (28 loc) · 866 Bytes
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
//Create a group of Posix threads from the main program
#include <iostream>
#include <pthread.h>
static const int num_threads = 10;
typedef struct {
int thread_id;
} thread_data;
//This function will be called from a thread
void *call_from_thread(void *args) {
thread_data *my_data = (thread_data *) args;
std::cout << "Launched by thread " << my_data->thread_id << std::endl;
return NULL;
}
int main() {
pthread_t t[num_threads];
thread_data td[num_threads];
//Launch a group of threads
for (int i = 0; i < num_threads; ++i) {
td[i].thread_id = i;
pthread_create(&t[i], NULL, call_from_thread, (void *) &td[i]);
}
std::cout << "Launched from the main\n";
//Join the threads with the main thread
for (int i = 0; i < num_threads; ++i) {
pthread_join(t[i], NULL);
}
return 0;
}