Semaphore and threads in C

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Semaphore and threads in C相关的知识,希望对你有一定的参考价值。

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");

以上是关于Semaphore and threads in C的主要内容,如果未能解决你的问题,请参考以下文章

java Semaphore信号亮-同意多个任务同一时候訪问这个资源--thinking in java21.7.6

Threading and Tasks in Chrome

python - threading-semaphore 示例

a simple example of thread and runnable in java

threading 之 semaphore信号量

python threading Semaphore