Created
June 19, 2015 14:49
-
-
Save bsubei/6aa299c740672aca7c46 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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