CSE
451: Introduction to Operating Systems
Section 5, April/26/2001
Jochen Jäger
1.
Project
2 turn in
2.
Project
3 hand out
3.
pthread
4.
threads
on other systems
Threadpool_test.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include "threadpool.h"
extern int errno;
void dispatch_to_me(void *arg) {
int seconds = (int) arg;
fprintf(stdout, " in dispatch %d\n", seconds);
sleep(seconds);
fprintf(stdout, " done dispatch %d\n", seconds);
}
int main(int argc, char **argv) {
threadpool tp;
tp = create_threadpool(2);
fprintf(stdout, "**main** dispatch 3\n");
dispatch(tp, dispatch_to_me, (void *) 3);
fprintf(stdout, "**main** dispatch 6\n");
dispatch(tp, dispatch_to_me, (void *) 6);
fprintf(stdout, "**main** dispatch 7\n");
dispatch(tp, dispatch_to_me, (void *) 7);
fprintf(stdout, "**main** done first\n");
sleep(20);
fprintf(stdout, "\n\n");
fprintf(stdout, "**main** dispatch 3\n");
dispatch(tp, dispatch_to_me, (void *) 3);
fprintf(stdout, "**main** dispatch 6\n");
dispatch(tp, dispatch_to_me, (void *) 6);
fprintf(stdout, "**main** dispatch 7\n");
dispatch(tp, dispatch_to_me, (void *) 7);
fprintf(stdout, "**main done second\n");
sleep(20);
exit(-1);
}
int pthread_create(pthread_t * thread,
pthread_attr_t * attr, void * (*start_routine)(void *), void * arg);
pthread_create creates a new thread of control that executes concurrently with the calling thread.
Example for locking:
pthread_mutex_t Locker = PTHREAD_MUTEX_INITIALIZER;
...
pthread_mutex_lock(&Locker);
... do critical stuff
pthread_mutex_unlock(&Locker);
#include
<pthread.h>
#include <stdio.h>
void *child(void *) {
printf("child\n");
int *result = new int; // storage for exit status
*result = 25; // exit-Status
return result;
}
int main() {
pthread_t pid;
void *res;
printf("Create child\n");
pthread_create(&pid,NULL,child,NULL);
printf("Pid of child: %d\n",pid);
pthread_join(pid,&res);
printf("result from child: %d\n",*(int *)res);
delete res;
}
Threads and synchronization
on other systems
Create a thread:
POSIX:
pthread_create(&threadID, &threadAttr,
threadRoutine, ThreadArg);
C:
cthread_t tid;
tid = cthread_fork(threadRoutine, threadArg);
Win32:
HANDLE hThread;
hThread = CreateThread(NULL, stackSize,
(LPTHREAD_START_ROUTINE) threadRoutine, (LPVOID) threadArg, 0, &threadId);
OS/2:
TID tid;
tid = _beginthread(threadRoutine, NULL, stackSize,
threadArg);
Thread Synchronization (e.g. Mutex locks):
POSIX:
pthread_mutex_t lock;
pthread_mutex_lock(&lock);
pthread_mutex_unlock(&lock);
C:
mutex_t lock;
mutex_lock(lock);
mutex_unlock(lock);
Win32:
HANDLE lock;
WaitForSingleObject(lock, INFINITE);
ReleaseMutex(lock);
OS/2:
HMTX lock;
DosRequestMutexSem(lock, timeOut);
DosReleaseMutexSem(lock);