互斥锁线程

互斥锁线程,第1张

互斥锁线程

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5015321.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-15

发表评论

登录后才能评论

评论列表(0条)

保存