2015-01-15 12:12:26 +03:00
|
|
|
/*
|
2015-01-15 18:58:55 +03:00
|
|
|
* WHAT THIS EXAMPLE DOES
|
2015-01-15 12:12:26 +03:00
|
|
|
*
|
2015-01-15 18:58:55 +03:00
|
|
|
* We create a pool of 4 threads and then add 40 tasks to the pool(20 task1
|
2015-01-18 02:16:35 +03:00
|
|
|
* functions and 20 task2 functions). task1 and task2 simply print which thread is running them.
|
2015-01-15 12:12:26 +03:00
|
|
|
*
|
2015-01-18 02:16:35 +03:00
|
|
|
* As soon as we add the tasks to the pool, the threads will run them. It can happen that
|
|
|
|
* you see a single thread running all the tasks (highly unlikely). It is up the OS to
|
|
|
|
* decide which thread will run what. So it is not an error of the thread pool but rather
|
|
|
|
* a decision of the OS.
|
2015-01-15 12:12:26 +03:00
|
|
|
*
|
|
|
|
* */
|
|
|
|
|
|
|
|
#include <stdio.h>
|
2015-11-24 07:47:50 +03:00
|
|
|
#include <pthread.h>
|
2015-01-15 12:12:26 +03:00
|
|
|
#include "thpool.h"
|
|
|
|
|
|
|
|
|
|
|
|
void task1(){
|
2015-01-16 22:38:22 +03:00
|
|
|
printf("Thread #%u working on task1\n", (int)pthread_self());
|
2015-01-15 12:12:26 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2015-01-15 18:58:55 +03:00
|
|
|
void task2(){
|
2015-01-16 22:38:22 +03:00
|
|
|
printf("Thread #%u working on task2\n", (int)pthread_self());
|
2015-01-15 12:12:26 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
int main(){
|
|
|
|
|
2015-01-15 18:58:55 +03:00
|
|
|
puts("Making threadpool with 4 threads");
|
2015-01-17 22:42:32 +03:00
|
|
|
threadpool thpool = thpool_init(4);
|
2015-01-15 12:12:26 +03:00
|
|
|
|
2015-01-15 18:58:55 +03:00
|
|
|
puts("Adding 40 tasks to threadpool");
|
|
|
|
int i;
|
|
|
|
for (i=0; i<20; i++){
|
2015-01-17 22:42:32 +03:00
|
|
|
thpool_add_work(thpool, (void*)task1, NULL);
|
|
|
|
thpool_add_work(thpool, (void*)task2, NULL);
|
2015-01-15 12:12:26 +03:00
|
|
|
};
|
|
|
|
|
2015-01-18 02:16:35 +03:00
|
|
|
puts("Killing threadpool");
|
2015-01-17 22:42:32 +03:00
|
|
|
thpool_destroy(thpool);
|
2015-01-15 12:12:26 +03:00
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|