Thread API: Xiaohua Lu Office: CS 3310 Tel.: 2621721 Email: Lxh@cs - Wisc.edu Office Hours: 11-12,3-5 T, TR
Thread API: Xiaohua Lu Office: CS 3310 Tel.: 2621721 Email: Lxh@cs - Wisc.edu Office Hours: 11-12,3-5 T, TR
Thread API: Xiaohua Lu Office: CS 3310 Tel.: 2621721 Email: Lxh@cs - Wisc.edu Office Hours: 11-12,3-5 T, TR
Xiaohua Lu Office : CS 3310 Tel. : 2621721 Email : [email protected] Office hours: 11-12,3-5 T,TR
Pthread API
thread creation & termination thread synchronization
mutex condition variable semaphore
Thread creation
status = pthread_create(&thread,&attr,start_function,arg);
int status; pthread_t thread;
pthread_attr_t attr;
void *start_function(void *arg); status: 0 if succeed and thread would contain the new thread id, otherwise EAGAIN or EINVAL.
pthread_t thread_id;
pthread_attr_t thread_attr; void *request_process(void *arg){
}
if ((status=pthread_attr_init(&thread_attr) ) != 0){ ... }
Mutex
pthread_mutex_t mutex; const pthread_mutexattr_t attr; int status; status = pthread_mutex_init(&mutex,&attr);
Thread i
status = pthread_mutex_destroy(&mutex);
status = pthread_mutex_unlock(&mutex); status = pthread_mutex_lock(&mutex); - block status = pthread_mutex_trylock(&mutex); - unblock
Condition variables
int status; pthread_condition_t cond; const pthread_condattr_t attr; pthread_mutex mutex; status = pthread_cond_init(&cond,&attr); status = pthread_cond_destroy(&cond);
status = pthread_cond_signal(&cond);
status = pthread_cond_broadcast(&cond);
Condition variables
status = pthread_cond_wait(&cond,&mutex); wait on a condition variable. First, a thread needs to get the lock of the mutex. Then it could check whether or not a condition is satisfied. If so, it could continue its work and unlock the mutex later. Otherwise, it would wait until some thread use pthread_signal to notify it that the condition is satisfied. It will release the mutex while waiting and automatically regain it when awoken.
An example of pthread_cond_wait()
If there are lots of sending threads and each needs first check whether or not the sending buffers are available. If so, they could send, otherwise they should wait for the next available buffer.
// For exclusive accessing of the number of available buffers if ( pthread_mutex_lock( &m_mutexSend ) < 0 ){ SHOW_ERROR( "Locking mutex failed" ); return RTP_ERROR; } // Check if Sending buffers are available while ( m_nOutWndBufs <= 0 ) { if ( pthread_cond_wait( &m_condSend, &m_mutexSend ) < 0 ) { SHOW_ERROR( "Waiting on condition variable failed" ); pthread_mutex_unlock( &m_mutexSend ); return RTP_ERROR; }
Semaphore
int status,pshared; sem_t sem; unsigned int initial_value; status = sem_init(&sem,pshared,initial_value); status = sem_destroy(&sem); status = sem_post(&sem);
Clarification of assignment 1
Timestamp = files last modification time? At most 32 concurrent client requests. client server_address filepath+filename server address should allow formats like localhost, nova23.cs.wisc.edu and 128.105.120.123