1

For a certain project,I have to use the static mutex initializer in pthread.However my library is supposed to be portable on Windows as well.

pthread_mutex_t csapi_mutex = PTHREAD_MUTEX_INITIALIZER;

Is there a corrosponding static initializer on windows.?

Thanks.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
liv2hak
  • 14,472
  • 53
  • 157
  • 270
  • yes, PTHREAD_MUTEX_INITIALIZER. – Vinicius Kamakura Jul 12 '11 at 23:43
  • does this mean the same code will work on windows? – liv2hak Jul 12 '11 at 23:46
  • if you are going to use pthreads on windows, yes. But to use pthreads on windows you need Cygwin – Vinicius Kamakura Jul 12 '11 at 23:48
  • No.I am planning to use it on a native windows system.I want to know if there is a corrosponding static initializer available in windows native systems. – liv2hak Jul 12 '11 at 23:53
  • 1
    if you are planning on using native stuff, you can't use pthreads, because pthreads isn't native. You would have to use window's mutexes, and they are not a `pthread_mutex_t`. http://msdn.microsoft.com/en-us/library/ms686927(v=vs.85).aspx – Vinicius Kamakura Jul 12 '11 at 23:56
  • Does this answer your question? [How to run pthreads on windows](https://stackoverflow.com/questions/7542286/how-to-run-pthreads-on-windows) – Henke Nov 29 '20 at 14:31
  • Does this answer your question? [Is it possible to do static initialization of mutexes in Windows?](https://stackoverflow.com/questions/3555859/is-it-possible-to-do-static-initialization-of-mutexes-in-windows) – Tsyvarev Dec 01 '20 at 10:38

2 Answers2

4

Pthreads-win32 should provide very good support for such constructs. But I have not checked.

wallyk
  • 56,922
  • 16
  • 83
  • 148
2

I came up with this port of pthread-compatible mutex operations:

#define MUTEX_TYPE             HANDLE
#define MUTEX_INITIALIZER      NULL
#define MUTEX_SETUP(x)         (x) = CreateMutex(NULL, FALSE, NULL)
#define MUTEX_CLEANUP(x)       (CloseHandle(x) == 0)
#define MUTEX_LOCK(x)          emulate_pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x)        (ReleaseMutex(x) == 0)

int emulate_pthread_mutex_lock(volatile MUTEX_TYPE *mx)
{ if (*mx == NULL) /* static initializer? */
  { HANDLE p = CreateMutex(NULL, FALSE, NULL);
    if (InterlockedCompareExchangePointer((PVOID*)mx, (PVOID)p, NULL) != NULL)
      CloseHandle(p);
  }
  return WaitForSingleObject(*mx, INFINITE) == WAIT_FAILED;
}

Basically, you want the initialization to happen atomically when the lock is used the first time. If two threads enter the if-body, then only one succeeds in initializing the lock. Note that there is no need to CloseHandle() for the static lock's lifetime.

Dr. Alex RE
  • 1,772
  • 1
  • 15
  • 23