Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing atomicly two scalar fields

In a multi-threaded (Linux/amd64, Pthreads, C11) application I have a struct (momitem_st in monimelt.h) containing notably two fields

uint16_t i_paylkind;
void* i_payload;

(if needed, I could change the type of i_paylkind to some other integral type, e.g. uintptr_t or atomic_uint)

FWIW, i_paylkind is a discriminant defining the actual struct runtime-type the i_payload is pointing to.

Is it possible to access these two fields atomically (w.r.t. other threads accessing the same struct). Of course I also have a pthread_mutex_t i_mtx; in the same structure which I could lock (using pthread_mutex_lock). But for performance reasons I might want to avoid that (perhaps transactional memory might be relevant)

It looks like <stdtomic.h> does not provide any machinery for that.

(question related to my MELT monitor GPLv3+ software)

like image 443
Basile Starynkevitch Avatar asked Dec 09 '14 13:12

Basile Starynkevitch


1 Answers

If you have really a C11 compiler, the _Atomic qualifier applies to any data type. Just use it. For struct types, the only things that you can do is load and store, unfortunately, you don't have access to the individual members.

like image 179
Jens Gustedt Avatar answered Oct 21 '22 04:10

Jens Gustedt