anutka

Untitled

Apr 4th, 2021
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.82 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <stdatomic.h>
  6. #include <inttypes.h>
  7.  
  8. typedef struct {
  9.     unsigned int thread_num;
  10.     unsigned int values_cnt;
  11. } arguments;
  12.  
  13. typedef struct Item {
  14.   _Atomic (struct Item *)next;
  15.   int64_t  value;
  16. } item_t;
  17.  
  18. _Atomic (item_t*) head = NULL;
  19.  
  20. void add_value(int64_t  value) {
  21.    item_t* new_item = (item_t*) malloc(sizeof(item_t));
  22.    new_item->next = atomic_exchange(&head, new_item);
  23.    new_item->value = value;
  24. }
  25.  
  26. void* add_values(void* arg) {
  27.     arguments args = * (arguments*)arg;
  28.     for (int64_t i = (args.thread_num + 1)*args.values_cnt-1; i >= args.thread_num*args.values_cnt; i--) {
  29.         add_value(i);
  30.         sched_yield();
  31.     }
  32. }
  33.  
  34. int main(int argc, char* argv[]) {
  35.     int thread_cnt = atoi(argv[1]);
  36.     int values_cnt = atoi(argv[2]);
  37.  
  38.     item_t* last_item = (item_t*) malloc(sizeof(item_t));
  39.     last_item->next = NULL;
  40.     last_item->value = -1;
  41.     atomic_store(&head, last_item);
  42.  
  43.     pthread_t thread[thread_cnt];
  44.     arguments args_to_pass[thread_cnt];
  45.  
  46.     pthread_attr_t threads_attr;
  47.     int page_size = 4096;
  48.     pthread_attr_init(&threads_attr);
  49.     pthread_attr_setstacksize(&threads_attr, page_size);
  50.  
  51.     for (int  i = 0; i < thread_cnt; i++) {
  52.         args_to_pass[i].thread_num = i;
  53.         args_to_pass[i].values_cnt = values_cnt;
  54.         pthread_create(&thread[i], &threads_attr, add_values, (void*) &args_to_pass[i]);
  55.     }
  56.    
  57.     for (int  i = 0; i < thread_cnt; i++) {
  58.         pthread_join(thread[i], NULL);
  59.     }
  60.  
  61.     pthread_attr_destroy(&threads_attr);
  62.    
  63.     for (item_t* i = atomic_load(&head); i->value != -1;) {
  64.         printf("%" PRId64 "\n", i->value);
  65.         item_t* cur = i;
  66.         i = cur->next;
  67.         free(cur);
  68.     }
  69.     free(last_item);
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment