-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.c
More file actions
77 lines (57 loc) · 1.97 KB
/
basic.c
File metadata and controls
77 lines (57 loc) · 1.97 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
// ***************************************************************************************
// Project: dthreads -> https://github.com/dezashibi-c/dthreads
// File: basic.c
// Date: 2024-08-14
// Author: Navid Dezashibi
// Contact: navid@dezashibi.com
// Website: https://www.dezashibi.com | https://github.com/dezashibi
// License:
// Please refer to the LICENSE file, repository or website for more information about
// the licensing of this work. If you have any questions or concerns,
// please feel free to contact me at the email address provided above.
// ***************************************************************************************
// * Description: Refer to readme for documentation or dthread.h
// ***************************************************************************************
#define DTHREAD_IMPL
#define DTHREAD_DEBUG
#include "../dthreads/dthread.h"
#include <stdio.h>
#define NUM_THREADS 4
long value = 12000;
DThreadMutex mutex;
dthread_define_routine(thread_func)
{
(void)data;
dthread_mutex_lock(&mutex);
value += 1;
dthread_debug_args("----- value is now %lu", value);
dthread_mutex_unlock(&mutex);
return NULL;
}
int main(void)
{
DThread threads[NUM_THREADS];
dthread_debug_args("----- value started at %lu", value);
// Initialize mutex
dthread_mutex_init(&mutex, NULL);
// Create threads
for (int i = 0; i < NUM_THREADS; ++i)
{
threads[i] = dthread_init_thread(thread_func, NULL);
if (dthread_create(&threads[i], NULL) != 0)
{
fprintf(stderr, "Failed to create thread %d\n", i);
return EXIT_FAILURE;
}
}
// Wait for all threads to finish
for (int i = 0; i < NUM_THREADS; ++i)
{
dthread_join(&threads[i]);
}
// Cleanup mutex
dthread_mutex_destroy(&mutex);
dthread_debug_args("----- value finished with %lu", value);
printf("final result: %lu\n", value);
return 0;
}