1//------------------------------------------------------------------------------
2// Copyright (c) 2016 by Lukasz Janyst <lukasz@jany.st>
3//------------------------------------------------------------------------------
4// This file is part of thread-bites.
5//
6// thread-bites is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// thread-bites is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with thread-bites. If not, see <http://www.gnu.org/licenses/>.
18//------------------------------------------------------------------------------
19
20#include <tb.h>
21#include <string.h>
22
23//------------------------------------------------------------------------------
24// The once initializer
25//------------------------------------------------------------------------------
26void once_func()
27{
28 tbprint("[thread 0x%llx] Running the once function\n", tbthread_self());
29 tbsleep(5);
30}
31
32tbthread_once_t once = TBTHREAD_ONCE_INIT;
33
34//------------------------------------------------------------------------------
35// Thread function
36//------------------------------------------------------------------------------
37void *thread_func(void *arg)
38{
39 tbthread_t self = tbthread_self();
40 tbprint("[thread 0x%llx] About to run the once function\n", self);
41 tbthread_once(&once, once_func);
42 tbprint("[thread 0x%llx] Finished running the once function\n", self);
43 return 0;
44}
45
46//------------------------------------------------------------------------------
47// Start the show
48//------------------------------------------------------------------------------
49int main(int argc, char **argv)
50{
51 tbthread_init();
52
53 tbthread_t thread[5];
54 int targ[5];
55 tbthread_attr_t attr;
56 int st = 0;
57
58 //----------------------------------------------------------------------------
59 // Spawn the threads
60 //----------------------------------------------------------------------------
61 tbthread_attr_init(&attr);
62 for(int i = 0; i < 5; ++i) {
63 targ[i] = i;
64 st = tbthread_create(&thread[i], &attr, thread_func, &targ[i]);
65 if(st != 0) {
66 tbprint("Failed to spawn thread %d: %s\n", i, tbstrerror(-st));
67 goto exit;
68 }
69 }
70
71 tbprint("[thread main] Threads spawned successfully\n");
72
73 for(int i = 0; i < 5; ++i) {
74 st = tbthread_join(thread[i], 0);
75 if(st != 0) {
76 tbprint("Failed to join thread %d: %s\n", i, tbstrerror(-st));
77 goto exit;
78 }
79 }
80
81 tbprint("[thread main] Threads joined\n");
82
83exit:
84 tbthread_finit();
85 return st;
86};
87