semaphore between 2 cores

Hi guys,

I got two different cores (different processors) which both access a certain global variable (gVar) in a shared memory.

I'd like to implement (by SW) a Semaphore so that when core A reads gVar, Core B would not attempt to write it, and vice versa.

How would you implement such Semaphore by SW?

Thank you.
by SW
What does "by SW" mean?
Hi KBW,

As simple as it sounds, by writing code in each of the cores.

Without using special Core instruction supported by HW, which not all cores have.
Last edited on
1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <mutex>
mutex m;
int var;

void f1()
{
m.lock()
var = 1;
m.unlock();
}


int f2()
{
m.lock()
int res = var;
m.unlock();
return res;
}


2)
1
2
3
4
5
6
7
8
9
10
11
12
#include <atomic>
atomic_int var;

void f1()
{
var = 1;
}

int v2()
{
return var;
}
Last edited on
Hi Konstantin,

Could you please explain these functions?

Where do they run?

Note that we discuss here 2 cores, not 2 processes on the same core.
I initially thought this was a programming question.

To be honest, I don't know the answer to your question. But what I do know, is that there isn't a single answer and each "type" of processor may have a different answer.

For example, a major difference between the 80386 and 80486 is the latter has support for multi CPU systems. It achieves this by pushing the problem of synchronisation out to the memory bus. The CPU can have an instruction restarted if necessary. I can't imagine a solution that sits on this will be compatible with a basic implementation.

But like I said, I don't know the answer to your question.
Hi KBW,

Thank you again friend.

I'm actually looking for a creative solution.

For example,
Each Core will read the gVar twice, until it gets identical reads.

However, it's not good enough..

Do you have a creative solution for that?
No, that's a recipe for a deadlock.
Hi kbw,
I don't think a deadlock can happen in this case.
Can you explain please?
Note that we discuss here 2 cores, not 2 processes on the same core.
Two different thread are potentially executed on different cores (it is up to OS sheduler).

Atomic variables are those, operation on which cannot be interrupted. So when reading, nothing can write in the middle of the read etc.

On x86 reads and write of aligned memory are guaranteed to be atomic. So if your variable is integral variable no larger than register size (32 or 64 bit), you can use atomic types for no cost and get thread safety.

Otherwise you need mutex. Mutex is the thread-safe varable you can safely try to acquire and do operation on some other non-safe variable, while other threads who want to access same variable will have to wait their turn.

Basicly atomics are inherently safe, when mutex is like thread-safe flag denoting if it is safe to access shared memory.
Last edited on
Topic archived. No new replies allowed.