libuv thread example
更新記錄
item | note |
---|---|
20160517 | 第一版 |
目錄
libuv thead
- 目前存在两个主流的线程库, Windows 线程库实现和 pthreads,reference
- pthreads - POSIX threads
- A single process can contain multiple threads, all of which are executing the same program
範例說明
- 參考來源
- source code
- uv_thread_create
- getrlimit (&lim)
- pthread_attr_setstacksize(attr,rlim_cur)
- pthread_create
- uv_thread_join
- pthread_join(*tid, NULL)
- pthreads - POSIX threads
範例內容
1 | int main() { |
範例測試
1 | [ubuntu](master-4113bbf)1h18m root@e8b0cd737680:[t11_thread-create]$ ./t11-main-ubuntu |
thread lock
读写锁是一种更细粒度的访问策略.两个线程可以同时访问共享内存区域, 当读线程拥有锁时, 写线程并不能获取到锁,reference
範例說明
- uv_barrier_init
- pthread_barrier_init
- pthread_mutex_init(&barrier->mutex, NULL); //如果參數attr爲NULL,則使用默認的互斥鎖屬性,默認屬性爲快速互斥鎖
- pthread_cond_init(&barrier->cond, NULL); // initialise condition variables
- uv_rwlock_init
- pthread_rwlock_init(rwlock,NULL)
- initialises the read-write lock referenced by rwlock with the attributes referenced by attr. If attr is NULL, the default read-write lock attributes are used,source
- uv_barrier_wait
- pthread_mutex_lock(&barrier->mutex);
- if(–barrier->count == 0 ) return..
- Otherwise, wait for other threads until the count reaches 0
- pthread_cond_wait //wait on a condition
- pthread_mutex_unlock(&barrier->mutex);
- uv_barrier_destroy
- barrier->count = 0;
- pthread_cond_destroy(&
barrier->cond); - pthread_mutex_destroy(&barrier->mutex);
範例內容
1 | int main() |
範例測試
- 不了解為何一開始只有..Reader1無2&3 ?
- 使用 uv_rwlock_rdlock(讀lock) /uv_rwlock_wrlock (寫lock)好處理,確保程式一至性(即在unlock之前是不會被中斷)
1 | [ubuntu](master-8af3563)0h20m root@e8b0cd737680:[t12_thread-lock]$ ./t12-main-ubuntu |