简体   繁体   中英

Linux pthread portability on windows

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM