simple example of Posix threads in C11, which doesn't have impl in gcc/clang. Remember to use -pthread as argument.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <stdio.h> | |
int *dowork(void *arg) | |
{ | |
pthread_t mythreadid = pthread_self(); | |
for (int i = 0; i < 5; i++) { | |
printf("Thread id: %lu, counter: %d, code: %s\n", mythreadid, i, (char *)arg); | |
} | |
return 0; | |
} | |
int main(void) { | |
pthread_t mythread; | |
// create a thread which executes a function | |
// former thrd_success | |
if (0 != pthread_create(&mythread, NULL, dowork, "Hello from a thread!")) { | |
printf("Could not create a thread.\n"); | |
return 1; | |
} | |
// join a thread to the main thread | |
pthread_join(mythread, NULL); | |
} |