ฉันได้เรียนรู้วิธีใช้ pthreads
และ mutexes แล้ว และฉันสับสนเกี่ยวกับผลลัพธ์ของโค้ด C ต่อไปนี้:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
void *TestThread(void *);
void TestFunc();
sem_t mutex;
int main(int argc, char *argv[]) {
pthread_t tid;
sem_init(&mutex, 1, 0);
pthread_create(&tid, NULL, TestThread, NULL);
pthread_join(tid, NULL);
}
void *TestThread(void *arg) {
int val;
sem_getvalue(&mutex, &val);
printf("value of mutex in Thread function: %d\n", val);
TestFunc();
pthread_exit(NULL);
}
void TestFunc() {
int val;
sem_getvalue(&mutex, &val);
printf("value of mutex in function in Thread function: %d\n", val);
}
จากนั้นฉันกำลังรวบรวมสิ่งนี้เช่น g++ -lpthread mutexTest.c -o mutexTest
และรันด้วย ./mutexText
ซึ่งให้และส่งออกเช่นนั้น
value of mutex in Thread function: 0
value of mutex in function in Thread function: 1754151134
เหตุใดค่า mutex จึงเปลี่ยนแปลงในฟังก์ชันที่ฉันเรียกภายในเธรด ฉันสูญเสียการอ้างอิงถึง mutex หรือไม่?
sem_init(&mutex, 0, 0);
หากสิ่งนี้เปลี่ยนแปลงพฤติกรรม โปรดแจ้งให้เราทราบ - person thb   schedule 13.03.2019Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 10.0.0 (clang-1000.10.44.4) Target: x86_64-apple-darwin18.2.0 Thread model: posix InstalledDir: /Library/Developer/CommandLineTools/usr/bin
- person TheStrangeQuark   schedule 13.03.2019gcc
และg++
เป็นทั้งนามแฝงสำหรับชุดคอมไพเลอร์ Mac ฉันไม่สามารถทำซ้ำบนกล่อง linux ของฉันได้ หวังว่าคนอื่นจะมี Mac - person bruceg   schedule 13.03.2019sem_getvalue()
ส่งคืนอะไรในทั้งสองกรณี หากคืนค่าไม่เป็นศูนย์errno
คืออะไรsem_getvalue()
บน Mac ดูเหมือนจะเป็นปัญหา ดู stackoverflow.com/questions/ 16655153/ และ stackoverflow.com/questions/23146950/ - person Andrew Henle   schedule 13.03.2019errno
ถูกตั้งค่าเป็น 78 ในทั้งสองกรณี ปรากฏว่าไม่ได้ตั้งค่าฟังก์ชันนี้ น่าสนใจ. - person TheStrangeQuark   schedule 13.03.2019-Wall
เสมอ - person user3386109   schedule 13.03.2019errno
ถูกตั้งค่าเป็น 0 ในทั้งสองกรณี สำหรับข้อมูลนี้ ฉันกำลังรวบรวมด้วย-Wall
และแน่นอน-Wextra -Werror
ด้วย - person thb   schedule 13.03.2019pthread_mutex_create
,pthread_mutex_lock
และpthread_mutex_unlock
- person user3386109   schedule 13.03.2019