Posix thread notes
Posted on 19 Ağustos 2015 in Programlama by admin
pthread_once example
(https://computing.llnl.gov/tutorials/pthreads/man/pthread_once.txt)
Save following code as main.c and compile with the given command.
#include <stdio.h> #include <pthread.h> pthread_once_t once_control = PTHREAD_ONCE_INIT; void library_init( void ) { printf ("pthread once\n"); } void * library_entry_point1(void *p1) { pthread_once( &once_control, library_init ); } void * library_entry_point2(void *p2) { pthread_once( &once_control, library_init ); } int main () { pthread_t t1, t2; pthread_create(&t1, NULL, library_entry_point1, (void*)NULL); pthread_create(&t2, NULL, library_entry_point2, (void*)NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; }
compile as gcc main.c -o main -lpthread
Difference between pthread_rwlock_wrlock and pthread_mutex_lock
The pthread_mutex_lock is a general purpose lock object. The
locking thread causes all other threads that use that mutex to block.
Very simple. The pthread_rwlock_wrlock() and its sibling
pthread_rwlock_rdlock() implement a reader-writer strategy there are
many readers and a few writers. The basic issue is that you want to
allow reader threads to proceed, but you want to block writers. If a
writer thread calls pthread_rwlock_wrlock(), it will block if a reader
thread has called the rdlock, but it will also block subsequent
readers. So basically, in your question, if you only use wrlock() then
the effect is the same as the standard mutex lock, but it appears
there is more overhead associated with it.