您需要做的是调用 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("%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 才能跨进程工作。