Created
March 13, 2014 07:24
-
-
Save vo/9523308 to your computer and use it in GitHub Desktop.
Stupid simple Pthread example for reference
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
#include <iostream> | |
#include <cstdio> | |
#include <pthread.h> | |
#include <unistd.h> | |
typedef struct { | |
int thread_num; | |
} data_t; | |
void *task (void * data) { | |
data_t * d = (data_t *) data; | |
for(int i = 0; i < 100; ++i) { | |
printf("test %d %d\n", d->thread_num, i); | |
usleep(500000); | |
} | |
} | |
int main () { | |
pthread_t pool[100]; | |
data_t data[100]; | |
// create 100 threads running the task | |
for(int i = 0; i < 100; ++i) { | |
data[i].thread_num = i; | |
pthread_create(&pool[i], NULL, task, &data[i]); | |
} | |
// wait for all the threads to finish | |
for(int i = 0; i < 100; ++i) | |
pthread_join(pool[i], NULL); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment