Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
EDAF55
C-camera
Commits
be0c7a98
Commit
be0c7a98
authored
Oct 20, 2017
by
Sven Gestegård Robertz
Browse files
thread example mutex_init
parent
e68956fa
Changes
1
Hide whitespace changes
Inline
Side-by-side
thread_examples/thread_example_semaphore.c
View file @
be0c7a98
...
...
@@ -12,12 +12,11 @@
struct
global_data
{
int
count
;
pthread_mutex_t
mtx
;
sem_t
sem_a
;
sem_t
sem_b
;
};
pthread_mutex_t
mtx
=
PTHREAD_MUTEX_INITIALIZER
;
void
*
task_a
(
void
*
ctx
)
{
struct
global_data
*
d
=
ctx
;
...
...
@@ -26,10 +25,10 @@ void * task_a(void * ctx)
printf
(
"started task_a
\n
"
);
for
(
i
=
0
;
i
<
d
->
count
;
++
i
){
sem_wait
(
&
d
->
sem_a
);
pthread_mutex_lock
(
&
mtx
);
pthread_mutex_lock
(
&
d
->
mtx
);
printf
(
"task_a: %d
\n
"
,
i
);
sem_post
(
&
d
->
sem_b
);
pthread_mutex_unlock
(
&
mtx
);
pthread_mutex_unlock
(
&
d
->
mtx
);
}
return
NULL
;
}
...
...
@@ -42,10 +41,10 @@ void * task_b(void * ctx)
printf
(
"started task_b
\n
"
);
for
(
i
=
0
;
i
<
d
->
count
;
++
i
){
sem_wait
(
&
d
->
sem_b
);
pthread_mutex_lock
(
&
mtx
);
pthread_mutex_lock
(
&
d
->
mtx
);
printf
(
"task_b: %d
\n
"
,
i
);
sem_post
(
&
d
->
sem_a
);
pthread_mutex_unlock
(
&
mtx
);
pthread_mutex_unlock
(
&
d
->
mtx
);
}
return
NULL
;
}
...
...
@@ -53,6 +52,7 @@ void * task_b(void * ctx)
int
global_data_init
(
struct
global_data
*
d
)
{
d
->
count
=
10
;
pthread_mutex_init
(
&
d
->
mtx
,
NULL
);
if
(
sem_init
(
&
d
->
sem_a
,
0
,
0
)){
return
1
;
}
...
...
@@ -85,10 +85,10 @@ int main()
exit
(
3
);
}
sleep
(
1
);
pthread_mutex_lock
(
&
mtx
);
pthread_mutex_lock
(
&
data
.
mtx
);
printf
(
"signalling semaphore
\n
"
);
sem_post
(
&
data
.
sem_a
);
pthread_mutex_unlock
(
&
mtx
);
pthread_mutex_unlock
(
&
data
.
mtx
);
pthread_join
(
thread_a
,
NULL
);
pthread_join
(
thread_b
,
NULL
);
return
0
;
...
...
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment