Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <error.h>
- #define NTHREADS 4
- static int k = 0;
- struct thread_info{
- pthread_t thread_id;
- pthread_mutex_t lock;
- int x;
- int a[10];
- };
- void* fkt(void* arg){
- struct thread_info* tinfo = (struct thread_info*) arg;
- if(pthread_mutex_lock(&tinfo->lock)) perror("mutex_lock");
- printf("THREAD %d with argument %dn", (int) tinfo->thread_id, tinfo->x);
- tinfo->a[k] = tinfo->x * tinfo->x;
- k++;
- if(pthread_mutex_unlock(&tinfo->lock)) perror("mutex_unlock");
- pthread_exit(NULL);
- }
- int main(){
- struct thread_info* tinfo = NULL;
- tinfo->x = 5;
- if(pthread_mutex_init(&tinfo->lock, NULL)) perror("mutex_init");
- for(int i = 0; i < NTHREADS; i++){
- if(pthread_create(&tinfo[i].thread_id, NULL, &fkt, &tinfo)) perror("pthread_create");
- }
- for(int i = 0; i < NTHREADS; i++){
- if(pthread_join(tinfo[i].thread_id, NULL)) perror("pthread_join");
- printf("THREAD JOINED: %dn", (int) tinfo->thread_id);
- }
- for(int i = 0; i < 10; i++){
- printf("[%d]t", tinfo->a[i]);
- }
- printf("n");
- if(pthread_mutex_destroy(&tinfo->lock)) perror("mutex_destroy");
- return 0;
- }
Add Comment
Please, Sign In to add comment