Author: WhoAmI
Date: 20230523
email:kccddb@gmail.com
Copyright: CC BY-NC-SA
《荀子‧勸學》不積跬步,無以至千里;不積小流,無以成江海。
I. Mutex variables MUST be declared with type pthread_mutex_t, and must be initialized before they can be used.
II. 了解 pthread_mutex_lock / pthread_mutex_unlock 與可能問題和代價
III. 程式執行效率與startvation 等問題
POSIX thread (pthread) libraries
Multithreaded Programming (POSIX pthreads Tutorial)
這是一個使用pthread 的簡單 echo server!
請用 putty 測試, 您可能測試正常! 但是事實上 有 BUG!!!
但是這是有問題的server! 不穩定! 當您連線的 client 很快時就可能會出錯! Why?
HINT: //Get Client's FD 可能出問題! Why? 如何修改?
因此server 的網路程式必須更僅慎! 如有必要需壓力測試!
pthread_create - create a new thread
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg);
Compile and link with -pthread.
特別小心 void *restrict arg
pthread_join - join with a terminated thread
pthread_detach - detach a thread
pthread_exit - terminate calling thread
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
注意 有 BUG!!!
請找出來, 還有何時可能有問題? 如何修改?
Hint: malloc
修正 上面的 bug
請自行 補上
setsockopt SO_REUSEADDR 的處理
與 SIGPIPE signal 的處理
#define LONGSTRING(…) #VA_ARGS
簡單 pthread 版 web server
HW. double linked list (不考慮排序), thread 2,3 write new data, thread1 read and delete data, 您如何設計?