Skip to content

Instantly share code, notes, and snippets.

@exbotanical
Created February 3, 2023 05:04
Show Gist options
  • Save exbotanical/e58dfbf9676fee0014b304c1f111e904 to your computer and use it in GitHub Desktop.
Save exbotanical/e58dfbf9676fee0014b304c1f111e904 to your computer and use it in GitHub Desktop.
threading code listing from multi-threading series on YT
#include <pthread.h> // for POSIX threads
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> // for pause and sleep
void *thread_routine(void *arg) {
char *thread_id = (char *)arg;
while (1) {
printf("%s\n", thread_id);
sleep(3);
}
}
void thread_create() {
// opaque object
pthread_t thread;
// you can pass state to a thread
// but you CANNOT pass caller's local state OR stack memory
// MUST be heap or static because ea thread has its own stack (part of the
// exec ctx)
static char *thread_arg = "thread 1";
// pthread does NOT use errno
// all pthread functions return special error codes; 0 on success
// this is a fork point - NOT to be confused with the fork syscall
if (pthread_create(&thread, NULL, thread_routine, (void *)thread_arg) != 0) {
// error
exit(1);
}
}
// main function == main thread
int main(int argc, char const *argv[]) {
thread_create();
printf("blocked\n");
pause();
return 0;
}
// gcc threads_1.c -o main -lpthread
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment