Skip to content

Instantly share code, notes, and snippets.

@r00takaspin
Last active November 9, 2022 10:05
Show Gist options
  • Select an option

  • Save r00takaspin/1b0727bb77f90b1af7edfe834f1da976 to your computer and use it in GitHub Desktop.

Select an option

Save r00takaspin/1b0727bb77f90b1af7edfe834f1da976 to your computer and use it in GitHub Desktop.

Revisions

  1. r00takaspin revised this gist Nov 9, 2022. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion counter.c
    Original file line number Diff line number Diff line change
    @@ -23,7 +23,7 @@ void* writer(void *arg) {
    int main() {
    int writers_num = 8;

    pthread_t tid_writers[writers_num];
    pthread_t tid_writers[writers_num];

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
  2. r00takaspin created this gist Nov 9, 2022.
    51 changes: 51 additions & 0 deletions counter.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    #include <stdlib.h>
    #include <pthread.h>
    #include <stdio.h>
    #include <unistd.h>
    #include <assert.h>

    pthread_mutex_t lock;
    int counter = 0;

    #define MAX_ITER 100000

    void* writer(void *arg) {
    for(int i=0; i < MAX_ITER; i++)
    {
    pthread_mutex_lock(&lock);
    counter += 1;
    pthread_mutex_unlock(&lock);
    }

    return NULL;
    }

    int main() {
    int writers_num = 8;

    pthread_t tid_writers[writers_num];

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
    printf("\n mutex init failed\n");
    return 1;
    }

    for (int i=0; i < writers_num; i++)
    {
    if (pthread_create(&(tid_writers[i]), NULL, &writer, &i)!=0)
    {
    printf("\ncannot create writer thread\n");
    exit(0);
    }
    }

    for(int i=0; i < writers_num; i++)
    {
    pthread_join(tid_writers[i], NULL);
    }

    pthread_mutex_destroy(&lock);

    assert((MAX_ITER*writers_num==counter) && "counter failed");
    }