A thread is a basic unit of CPU utilization.
A thread shares with its peer threads its:
-code section
-data section
-operating-system resources
so take care when deal with global variable(can add mutext
lock or wait semaphore)
Synchronization:
http://www.csc.villanova.edu/~mdamian/threads/posixsem.html
can use POSIX semaphores:
int sem_init(sem_t *sem, int pshared, unsigned int value);
- sem points to a semaphore object to initialize
- pshared is a flag indicating whether or not the semaphore should
be shared with fork()ed processes. LinuxThreads does not currently
support shared semaphores - value is an initial value to set the semaphore to
To wait on a semaphore, use sem_wait:
int sem_wait(sem_t *sem);
Example of use:
sem_wait(&sem_name);
-
If the value of the semaphore is negative, the calling process blocks; one of the blocked
processes wakes up when another process calls sem_post.
To increment the value of a semaphore, use sem_post:
int sem_post(sem_t *sem);
Example of use:
sem_post(&sem_name);
-
It increments the value of the semaphore and wakes up a blocked process waiting on the
semaphore, if any.
notice that threads can work concurrently,and the speed you
don‘t know,so sometimes the value change is not as you think,so take care
(lab1.3,e0,e1,changing values of e0 and e1 first then sem_post(sem1)).
When the program stops somewhere, probably it‘s waiting a signal but hasn‘t arrived.
check carefully,may have deadlock.
Thread:
pthread_detach(pthread_self());//parent is not joining
use this for all threads created,the main_thread doesn‘t need to use pthread_join
because the resources occupied by these threads can be released automatically
after exiting.
Can‘t use kill() or signal() for threads,because they are for processes(like children
and parents),not for threads.
threads creation:
status=pthread_create(&th_a,NULL,read_thread1,&one);
if(status!=0)
printf("error to create thread 1");