Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <stdatomic.h>
- #include <inttypes.h>
- typedef struct {
- unsigned int thread_num;
- unsigned int values_cnt;
- } arguments;
- typedef struct Item {
- _Atomic (struct Item *)next;
- int64_t value;
- } item_t;
- _Atomic (item_t*) head = NULL;
- void add_value(int64_t value) {
- item_t* new_item = (item_t*) malloc(sizeof(item_t));
- new_item->next = atomic_exchange(&head, new_item);
- new_item->value = value;
- }
- void* add_values(void* arg) {
- arguments args = * (arguments*)arg;
- for (int64_t i = (args.thread_num + 1)*args.values_cnt-1; i >= args.thread_num*args.values_cnt; i--) {
- add_value(i);
- sched_yield();
- }
- }
- int main(int argc, char* argv[]) {
- int thread_cnt = atoi(argv[1]);
- int values_cnt = atoi(argv[2]);
- item_t* last_item = (item_t*) malloc(sizeof(item_t));
- last_item->next = NULL;
- last_item->value = -1;
- atomic_store(&head, last_item);
- pthread_t thread[thread_cnt];
- arguments args_to_pass[thread_cnt];
- pthread_attr_t threads_attr;
- int page_size = 4096;
- pthread_attr_init(&threads_attr);
- pthread_attr_setstacksize(&threads_attr, page_size);
- for (int i = 0; i < thread_cnt; i++) {
- args_to_pass[i].thread_num = i;
- args_to_pass[i].values_cnt = values_cnt;
- pthread_create(&thread[i], &threads_attr, add_values, (void*) &args_to_pass[i]);
- }
- for (int i = 0; i < thread_cnt; i++) {
- pthread_join(thread[i], NULL);
- }
- pthread_attr_destroy(&threads_attr);
- for (item_t* i = atomic_load(&head); i->value != -1;) {
- printf("%" PRId64 "\n", i->value);
- item_t* cur = i;
- i = cur->next;
- free(cur);
- }
- free(last_item);
- }
Advertisement
Add Comment
Please, Sign In to add comment