Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Busy waiting
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Example C code== The following [[C (programming language)|C]] code examples illustrate two threads that share a global [[integer]] '''i'''. The first thread uses busy-waiting to check for a change in the value of '''i''': <syntaxhighlight lang="c"> #include <pthread.h> #include <stdatomic.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> /* i is global, so it is visible to all functions. It makes use of the special * type atomic_int, which allows atomic memory accesses. */ atomic_int i = 0; /* f1 uses a spinlock to wait for i to change from 0. */ static void *f1(void *p) { int local_i; /* Atomically load current value of i into local_i and check if that value is zero */ while ((local_i = atomic_load(&i)) == 0) { /* do nothing - just keep checking over and over */ } printf("i's value has changed to %d.\n", local_i); return NULL; } static void *f2(void *p) { int local_i = 99; sleep(10); /* sleep for 10 seconds */ atomic_store(&i, local_i); printf("t2 has changed the value of i to %d.\n", local_i); return NULL; } int main() { int rc; pthread_t t1, t2; rc = pthread_create(&t1, NULL, f1, NULL); if (rc != 0) { fprintf(stderr, "pthread f1 failed\n"); return EXIT_FAILURE; } rc = pthread_create(&t2, NULL, f2, NULL); if (rc != 0) { fprintf(stderr, "pthread f2 failed\n"); return EXIT_FAILURE; } pthread_join(t1, NULL); pthread_join(t2, NULL); puts("All pthreads finished."); return 0; } </syntaxhighlight> In a use case like this, one can consider using [[C11 (C standard revision)|C11]]'s [[Monitor (synchronization)#Condition variables|condition variables]].
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)