user16118233
user16118233

Reputation:

How To Run Same Code Twice Using Threads?

I have this code in C:

int X=0;

void main()
{
    X++;
}

How can I let my CPU run this code twice nearly simultaneously on different cores (I'm not asking for 100% success rate for this scenario to happen)?

Maybe thread can help here?


I want to see in my eyes that after running the code X may be 1 and not 2.

If it's important my kernel is non-preemptive (linux 2.4).

Upvotes: 0

Views: 211

Answers (1)

Superlokkus
Superlokkus

Reputation: 5039

Hello and welcome to Stackoverflow. Your program could be as simple as

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

int x;

void func(void*) {
    x++;
    printf("x: %d\n", x);
}

int main() {
    pthread_t thread1;
    if (pthread_create(&thread1, NULL, &func, NULL)) {
        perror("Thread creation failed");
    };

    func(NULL);
    pthread_join(thread1, NULL);
}

However what you will get by this is a so called data race or race condition

If you really want to count just something concurrently, then an atomic could be what you need:

#include <stdatomic.h>

atomic_int x;

void func(void*) {
    atomic_fetch_add(&x,1);
    printf("x: %d\n", atomic_load(&x));
}

Furthermore this default thread should still be suitable, and you could use pthread_attr_setschedpolicy but I am not sure otherwise please elaborate more.

Upvotes: 1

Related Questions