您需要做的是调用pthread_mutex_lock来保护互斥锁,如下所示:
pthread_mutex_lock(&mutex);
一旦执行此 *** 作,
pthread_mutex_lock(mutex)在您
pthread_mutex_unlock在该线程中进行调用之前,不会再进行任何其他调用。因此,如果尝试调用pthread_create,则将能够创建一个新线程,并且该线程将能够(不正确地)使用共享资源。您应该
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("%dn", 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("%dn", p->sharedResource); pthread_mutex_unlock(&(p->mutex)); sleep(1); } munmap(p, sizeof(struct shared*)); shm_unlink("/foo");}
编写程序以更改p-> sharedResource留给读者练习。:-)
顺便说一句,忘了指出互斥对象必须设置PTHREAD_PROCESS_SHARED属性,这样pthread才能跨进程工作。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)