-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathposix_threads.cpp
More file actions
60 lines (50 loc) · 1.53 KB
/
posix_threads.cpp
File metadata and controls
60 lines (50 loc) · 1.53 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
// This program shows off multithreading basics using pthreads
// By: Nick from CoffeeBeforeArch
#include <pthread.h>
#include <iostream>
using namespace std;
#define NUM_THREADS 10
// Global pthread implementation of mutex lock
pthread_mutex_t mtx;
// Argument we will cast as void* for your thread function
struct Args {
int tid;
int data;
};
// pthread functions must have return type void*, with a void* arg
void *boring_thread_function(void *args) {
Args *local_args = (Args *)args;
// Get the lock before entering the critical section
pthread_mutex_lock(&mtx);
cout << "Printing from thread " << local_args->tid << endl;
cout << "Value of data is " << local_args->data << endl;
// Release the lock to someone else
pthread_mutex_unlock(&mtx);
}
int main() {
// Create an array of 10 threads
pthread_t threads[NUM_THREADS];
Args per_thread_args[NUM_THREADS];
// Create 10 threads
for (int i = 0; i < NUM_THREADS; i++) {
per_thread_args[i].tid = i;
per_thread_args[i].data = i * i;
// Launch the threads
/*
Arguments:
1.) Pointer to pthread_t
2.) Attributes for the thread (NULL means default)
3.) Entry routine
4.) Arguments
*/
pthread_create(&threads[i], NULL, boring_thread_function,
(void *)&per_thread_args[i]);
}
// Return code for the thread
void *ret;
// Wait for all threads to finish before exiting the program
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], &ret);
}
return 0;
}