Monday, 15 March 2010

c - Mutex lock threads -



c - Mutex lock threads -

am new multi threaded/processs programming. here's need clarify.

process code

pthread_mutex_lock() pthread_create(fooapi(sharedresource)) //fooapi creates thread shared resource shares across processes. pthread_mutex_unlock()

with above pseudo code, process b able access sharedresource if mutex not unlocked?

how can access sharedresource process b correctly?

any there clear visual diagram explains relationship between mutexes, threads , processes?

what need phone call pthread_mutex_lock secure mutex, this:

pthread_mutex_lock(&mutex);

once this, other calls pthread_mutex_lock(mutex) not homecoming until phone call pthread_mutex_unlock in thread. if seek phone call pthread_create, able create new thread, , thread able (incorrectly) utilize shared resource. should phone call pthread_mutex_lock within fooapi function, , cause function wait until shared resource available.

so have this:

#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 shared resource now.\n"); sharedresource = 42; pthread_mutex_unlock(&mutex); homecoming 0; } int main() { pthread_t thread; // not locking reason other create point. pthread_mutex_lock(&mutex); pthread_create(&thread, null, fooapi, null); sleep(1); pthread_mutex_unlock(&mutex); // need lock utilize shared resource. pthread_mutex_lock(&mutex); printf("%d\n", sharedresource); pthread_mutex_unlock(&mutex); }

edit: using resources across processes follows same basic approach, need map memory other process. here's illustration using 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; // create sure can 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; (i = 0; < 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"); }

writing programme create changes p->sharedresource left exercise reader. :-)

forgot note, way, mutex has have pthread_process_shared attribute set, pthreads work across processes.

c linux pthreads mutex multiprocess

No comments:

Post a Comment