是多线程/进程编程的新手。所以这是我需要澄清的。
处理代码
pthread_mutex_lock() pthread_create(fooAPI(sharedResource)) //fooAPI creates another thread with shared resource that shares across processes. pthread_mutex_unlock()
使用上述伪代码,sharedResource如果互斥锁未解锁,进程B是否可以访问?
sharedResource
如何从进程B正确访问sharedResource?
有没有清晰的可视化图表说明互斥体,线程和进程之间的关系?
您需要做的是调用pthread_mutex_lock来保护互斥锁,如下所示:
pthread_mutex_lock(&mutex);
一旦执行此操作,pthread_mutex_lock(mutex)在您pthread_mutex_unlock在该线程中进行调用之前,不会再进行任何其他调用。因此,如果尝试调用pthread_create,则将能够创建一个新线程,并且该线程将能够(不正确地)使用共享资源。您应该pthread_mutex_lock在fooAPI函数内部进行调用,这将导致函数等待,直到共享资源可用为止。
pthread_mutex_lock(mutex)
pthread_mutex_unlock
pthread_mutex_lock
fooAPI
所以你会有这样的事情:
#include <pthread.h> #include <stdio.h> int sharedResource = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* fooAPI(void* param) { pthread_mutex_lock(&mutex); printf("Changing the shared resource now.\n"); sharedResource = 42; pthread_mutex_unlock(&mutex); return 0; } int main() { pthread_t thread; // Really not locking for any reason other than to make the point. pthread_mutex_lock(&mutex); pthread_create(&thread, NULL, fooAPI, NULL); sleep(1); pthread_mutex_unlock(&mutex); // Now we need to lock to use the shared resource. pthread_mutex_lock(&mutex); printf("%d\n", sharedResource); pthread_mutex_unlock(&mutex); }
编辑:跨进程使用资源遵循相同的基本方法,但是您需要将内存映射到其他进程。这是使用shmem的示例:
#include <stdio.h> #include <unistd.h> #include <sys/file.h> #include <sys/mman.h> #include <sys/wait.h> struct shared { pthread_mutex_t mutex; int sharedResource; }; int main() { int fd = shm_open("/foo", O_CREAT | O_TRUNC | O_RDWR, 0600); ftruncate(fd, sizeof(struct shared)); struct shared *p = (struct shared*)mmap(0, sizeof(struct shared), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); p->sharedResource = 0; // Make sure it can be shared across processes pthread_mutexattr_t shared; pthread_mutexattr_init(&shared); pthread_mutexattr_setpshared(&shared, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&(p->mutex), &shared); int i; for (i = 0; i < 100; i++) { pthread_mutex_lock(&(p->mutex)); printf("%d\n", p->sharedResource); pthread_mutex_unlock(&(p->mutex)); sleep(1); } munmap(p, sizeof(struct shared*)); shm_unlink("/foo"); }
编写程序以更改p-> sharedResource留给读者练习。:-)
顺便说一句,忘了指出互斥对象必须设置PTHREAD_PROCESS_SHARED属性,这样pthread才能跨进程工作。