Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <time.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <semaphore.h>
- #define THREAD_COUNT 4
- pthread_t thread[THREAD_COUNT];
- typedef struct task_struct
- {
- void (*f)(void *p);
- void *argv;
- struct task_struct *next;
- } task_t;
- static sem_t task_count;
- static pthread_mutex_t task_mutex;
- static task_t *task_root;
- task_t* task_new(void (*f)(void *p), void *argv)
- {
- task_t *task;
- task = malloc(sizeof(task_t));
- task->f = f;
- task->argv = argv;
- task->next = NULL;
- return task;
- }
- void task_run(task_t *task)
- {
- task->f(task->argv);
- }
- void task_destroy(task_t *task)
- {
- free(task);
- }
- void* thread_body(void *p)
- {
- task_t *task;
- printf("Vlakno: %d\n", p);
- while(1)
- {
- sem_wait(&task_count);
- pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
- pthread_mutex_lock(&task_mutex);
- task = task_root;
- task_root = task_root->next;
- pthread_mutex_unlock(&task_mutex);
- //printf("Vlakno: X%d\n", p);
- task_run(task);
- task_destroy(task);
- fflush(stdout);
- pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
- }
- return NULL;
- }
- int work_init()
- {
- int i;
- sem_init(&task_count, 0, 0);
- pthread_mutex_init(&task_mutex, NULL);
- task_root = NULL;
- for(i = 0; i<THREAD_COUNT; i++)
- {
- pthread_create(&thread[i], NULL, thread_body, i);
- pthread_detach(thread[i]);
- }
- return 0;
- }
- int work_add_task(task_t *task)
- {
- task_t *task_actual;
- task_t *task_prev;
- pthread_mutex_lock(&task_mutex);
- if( task_root == NULL )
- {
- task_root = task;
- pthread_mutex_unlock(&task_mutex);
- sem_post(&task_count);
- return;
- }
- task_prev = NULL;
- task_actual = task_root;
- while( task_actual != NULL )
- {
- task_prev = task_actual;
- task_actual = task_actual->next;
- }
- task_prev->next = task;
- pthread_mutex_unlock(&task_mutex);
- sem_post(&task_count);
- return 0;
- }
- int work_cancel()
- {
- int i;
- for(i = 0; i<THREAD_COUNT; i++)
- {
- printf("cancel %p %d\n", &thread[i], i);
- pthread_cancel(thread[i]);
- }
- return 0;
- }
- int work_quit()
- {
- int i;
- pthread_mutex_destroy(&task_mutex);
- for(i = 0; i<THREAD_COUNT; i++)
- {
- pthread_join(thread[i], NULL);
- }
- return 0;
- }
- void action(void *p)
- {
- printf("%s\n", (char *)p);
- free(p);
- }
- int main()
- {
- int i;
- work_init();
- for(i = 0; i<100; i++)
- {
- char str[64];
- sprintf(str, "uloha %d", i);
- work_add_task(task_new(action, (void *)strdup(str)));
- }
- sleep(2);
- //work_cancel();
- work_quit();
- return 0;
- }
Add Comment
Please, Sign In to add comment