0

For example, I have a variable

struct sth {
    int abcd;
    pthread_mutex_t mutex;
};

I have two method

setSth(int a) {
  lock();
  sth->abcd = a;
  unlock();
}

getSth() {
  return sth->abcd;
}

sth will never be freed. Is it safe not use lock/unlock in getSth()? I don't care accuracy.

By safe I mean there's no segfault thing.

Sato
  • 8,192
  • 17
  • 60
  • 115
  • There is no "segfault thing", but it doesn't mean it's safe. It is safe to read/write an integer from different threads without locking if the operation is atomic. And whether it is an atomic operation, depends on many things, but most importantly on the architecture you are using. – Erki Aring Mar 16 '18 at 08:36
  • read is safe(i mean no segfault) but while the sth’s memory is valid. – Junhee Shin Mar 16 '18 at 08:36
  • See: https://stackoverflow.com/a/54242/3142427 – Erki Aring Mar 16 '18 at 08:38
  • "Lock a variable" is a very dangerous mental model. Synchronization primitives like mutex can do no such thing, they can only block code. As-is it is pretty unlikely to do anything useful and the int is already atomic. But real programs often need more than one variable and now it matters that the view is consistent. A named pipe is an alternative, you leave it up to the OS to provide the synchronization and the memory sharing. Much easier to reason through. – Hans Passant Mar 16 '18 at 08:48

0 Answers0