Created
October 22, 2011 02:57
-
-
Save dannluciano/1305513 to your computer and use it in GitHub Desktop.
A simple example for using thread in c/c++.
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
// usage: | |
// gcc -o thread threads.c | |
// ./thread time | |
// time is the number of seconds | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#define NUM_THREADS 3 | |
void *sleep_func(void *argument) | |
{ | |
int time = (atoi)(argument); | |
printf("Sleeping for %d seconds!\n", time); | |
sleep(time); | |
exit(EXIT_SUCCESS); | |
} | |
void *other_func(void *argument) | |
{ | |
while (true) | |
{ | |
/* printf("Hello Word With Threads!\n"); */ | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
pthread_t threads[NUM_THREADS]; | |
int thread_args[NUM_THREADS]; | |
int rc1, rc2, rc3, i; | |
/* setup all arguments */ | |
for (i=0; i<NUM_THREADS; ++i) | |
{ | |
thread_args[i] = i; | |
printf("In main: creating thread %d\n", i); | |
} | |
/* create all threads */ | |
rc1 = pthread_create(&threads[0], NULL, sleep_func, (void *) argv[1]); | |
rc2 = pthread_create(&threads[1], NULL, other_func, (void *) &thread_args[1]); | |
rc3 = pthread_create(&threads[2], NULL, other_func, (void *) &thread_args[2]); | |
/* wait for all threads to complete */ | |
rc1 = pthread_join(threads[0], NULL); | |
rc2 = pthread_join(threads[1], NULL); | |
rc3 = pthread_join(threads[2], NULL); | |
for (i=0; i<NUM_THREADS; ++i) | |
{ | |
thread_args[i] = i; | |
printf("In main: destroing thread %d\n", i); | |
} | |
exit(EXIT_SUCCESS); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget add parameter to execute.
like:
./thread 1
In main: creating thread 0
In main: creating thread 1
In main: creating thread 2
Sleeping for 1 seconds!