Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make a piece of code atomic (C#)?

When I said atomic, I meant set of instructions will execute without any context switching to another thread on the same process (other kinds of switches have to be done of course). The only solution I came up with is to suspend all threads except currently executed before part and resume them after it. Any more elegant way?

The reason I want to do that is to collect a coherent state of objects running on multiple threads. However, their code cannot be changed (they're already compiled), so I cannot insert mutexes, semaphores, etc in it. The atomic operation is of course state collecting (i.e. copying some variables).

like image 415
konrad.kruczynski Avatar asked Jan 07 '11 23:01

konrad.kruczynski


People also ask

Is ++ atomic in C?

On objects without an atomic type, standard never defines ++ as an atomic operation.

What is an atomic function in C?

Atomics as part of the C language are an optional feature that is available since C11. Their purpose is to ensure race-free access to variables that are shared between different threads. Without atomic qualification, the state of a shared variable would be undefined if two threads access it concurrently.

How atomic operations are implemented?

Atomic instructions bypass the store buffer or at least they act as if they do - they likely actually use the store buffer, but they flush it and the instruction pipeline before the load and wait for it to drain after, and have a lock on the cacheline that they take as part o the load, and release as part of the store ...


2 Answers

There are some atomic operations in the Interlocked class but it only provides a few very simple operations. It can't be used to create an entire atomic block of code.

I'd advise using locking carefully to make sure that your code will still work even if the context changes.

like image 131
Mark Byers Avatar answered Sep 30 '22 14:09

Mark Byers


Well, you can use locks, but you can't prevent context switching exactly. But if your threads lock on the same object, then the threads waiting obviously won't be running, so there's no context switching involved since there's nothing to run.

You might want to look at this page too.

like image 41
user541686 Avatar answered Sep 30 '22 16:09

user541686