Skip to content

2 thread simple counter incrementation with critical section inside coroutines example #49

@fskoras

Description

@fskoras

Please tell me what am I doing wrong?

Problem description

The program keep crashing randomly.
If I just use pthreads directly without coroutines it works without issues.

Specs

  • Windows 11
  • Compiler: MinGW-W64 gcc (x86_64-posix-seh-rev0, Built by MinGW-Builds project) 14.2.0

Example

#include <stdio.h>
#include <pthread.h>
#include <libco.h>

int counter = 0;                // Shared counter
pthread_mutex_t counter_mutex;  // Mutex to protect the counter

__thread cothread_t co_main;    // TLS main coroutine
__thread cothread_t co_thread;  // TLS coroutine

#define STACK_SIZE 0x40000

void co_increment_counter(void)
{
    // Lock the mutex before modifying the counter
    pthread_mutex_lock(&counter_mutex);
    counter++;  // Critical section
    // Unlock the mutex after modifying the counter
    pthread_mutex_unlock(&counter_mutex);
    co_switch(co_main);
}

// Thread function to increment the counter
void* increment_counter(void*) {
    co_main = co_active();
    
    for (int i = 0; i < 100000; ++i) {
        co_thread = co_create(STACK_SIZE, co_increment_counter);
        co_switch(co_thread);
        co_delete(co_thread);
    }
}

int main() {
    pthread_t thread1, thread2;

    // Create two threads
    if (pthread_create(&thread1, NULL, increment_counter, NULL)) {
        printf("Failed to create thread 1\n");
        return -1;
    }
    if (pthread_create(&thread2, NULL, increment_counter, NULL)) {
        printf("Failed to create thread 2\n");
        return -1;
    }

    // Wait for both threads to finish
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    // Destroy the mutex after usage
    pthread_mutex_destroy(&counter_mutex);

    // Print the final counter value
    printf("Final counter value: %d\n", counter);

    return 0;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions