Skip to content

Instantly share code, notes, and snippets.

@bsubei
Created June 19, 2015 14:49
Show Gist options
  • Save bsubei/6aa299c740672aca7c46 to your computer and use it in GitHub Desktop.
Save bsubei/6aa299c740672aca7c46 to your computer and use it in GitHub Desktop.
// Hello World for POSIX-threads
// compile using: gcc -o hello_thread hello_thread.c -lpthread
// then run like this: ./hello_thread 4
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *hello_world(void *thread_id) {
printf("Hello world from thread: %ld!\n", (long)thread_id);
}
int main(int argc, char** argv) {
if (argc < 2) {
printf("Usage: hello_thread num_threads\n");
pthread_exit(NULL);
}
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
printf("In main thread...\n");
long i;
for (i = 0; i < num_threads; i++) {
printf("Creating thread %ld\n", i);
int ret = pthread_create(&threads[i], NULL, &hello_world, (void *)i);
if(ret != 0) {
printf("Error: pthread_create() failed for thread %ld\n", i);
exit(EXIT_FAILURE);
}
}
pthread_exit(NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment