LINUX.ORG.RU

История изменений

Исправление i-rinat, (текущая версия) :

И еще раз повторю: мьютекс — это просто глобальный атомарный флаг!

Ты намеренно путаешь понятие и реализацию.

#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t lock = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;

void *thread_func(void *param) {
  printf("trying to unlock mutex in another thread\n");
  int ret = pthread_mutex_unlock(&lock);
  printf("ret = %d\n", ret);
  return NULL;
}

int main(void) {
  pthread_t t;

  pthread_mutex_lock(&lock);

  printf("starting thread\n");
  pthread_create(&t, NULL, thread_func, NULL);
  pthread_join(t, NULL);
  printf("joined\n");

  printf("unlocking in main thread\n");
  pthread_mutex_unlock(&lock);
  printf("unlocked\n");
  return 0;
}
$ ./a.out 
starting thread
trying to unlock mutex in another thread
ret = 1
joined
unlocking in main thread
unlocked
$ 

Исправление i-rinat, :

И еще раз повторю: мьютекс — это просто глобальный атомарный флаг!

Ты намеренно путаешь понятие и реализацию.

#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t lock = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;

void *thread_func(void *param) {
  printf("trying to unlock mutex in another thread\n");
  int ret = pthread_mutex_unlock(&lock);
  printf("ret = %d\n", ret);
  return NULL;
}

int main(void) {
  pthread_t t;

  pthread_mutex_lock(&lock);

  printf("starting thread\n");
  pthread_create(&t, NULL, thread_func, NULL);
  pthread_join(t, NULL);
  printf("joined\n");

  printf("unlocking in main thread\n");
  pthread_mutex_unlock(&lock);
  printf("unlocked\n");
  return 0;
}
$ ./a.out 
starting thread
trying to unlock mutex in other thread
ret = 1
joined
unlocking in main thread
unlocked
$ 

Исходная версия i-rinat, :

И еще раз повторю: мьютекс — это просто глобальный атомарный флаг!

Ты намеренно путаешь понятие и реализацию.

#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t lock = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;

void *thread_func(void *param) {
  printf("trying to unlock mutex in other thread\n");
  int ret = pthread_mutex_unlock(&lock);
  printf("ret = %d\n", ret);
  return NULL;
}

int main(void) {
  pthread_t t;

  pthread_mutex_lock(&lock);

  printf("starting thread\n");
  pthread_create(&t, NULL, thread_func, NULL);
  pthread_join(t, NULL);
  printf("joined\n");

  printf("unlocking in main thread\n");
  pthread_mutex_unlock(&lock);
  printf("unlocked\n");
  return 0;
}
$ ./a.out 
starting thread
trying to unlock mutex in other thread
ret = 1
joined
unlocking in main thread
unlocked
$