pthread简单的用法 pthread exit 用法

简单说一下semaphore,其实简单来理解,semaphore就是一个带锁的计数器,可以更方便的控制线程间的同步。(mutex用来控制对共享变量criticalsection的访问)。
pthread简单的用法 pthread exit 用法
比如实现一个读写者模式,1个writer,2个reader。 writer源源不断的往一个queue里写内容,假设semaphoer内部有个变量v,写完sem_post-->(v++);2个reader sem_wait(),当v>0时,reader会被激活自动v--,然后读取queue。这样就很方便的解决了多个writer/reader的同步问题,而不需要reader去轮询。
IntroductionPOSIX threads (pthreads) are astandardized interface on operating system threads.Compiling a pthreadsProgramRelevant headers aside (they arediscussed below), a program wishing to use pthreads must linkagainst the pthreads library. Here is an example invocation ofgccdemonstrating this:
gcc -pedantic-Wall -o theaded_program src.c -lpthreadThe -l flag specifies the name ofa library to link against (pthread, in our case); since pthreads isa system library, gcc knows where to find it.CreatingThreadsAny program using pthreads willneed to include pthread.h. Below is the Hello World of pthreadsprograms:#include#include
void *entry_point(void *arg){ printf("Helloworld!n");
returnNULL;}
int main(intargc, char **argv){ pthread_tthr; if(pthread_create(&thr, NULL, &entry_point,NULL)) { printf("Could not createthreadn"); return -1; }
if(pthread_join(thr, NULL)) { printf("Could not join threadn"); return -1; } return0;}There are two functions of notehere:• pthread_create: Spawns a newpthread using the given function as an entry point. This entrypoint can be considered the "main" function of that thread ofexecution.• pthread_join: Causes thecalling thread to wait until the given threadterminates.Another point worth noting isthat the thread entry point takes a single argument; the lastargument to pthread_create is the argument that is passed to theentry point.Similarly, threads can return avalue to the function that calls pthread_join on them. See the manpage for details.Exiting aThreadIn the above example, entry_pointreturns a NULL pointer to the thread that calls pthread_join on it.Sometimes, it may be desirable to exit a thread from some functionother than the entry point.#include#include
voidother_function(){ pthread_exit(NULL);}
void *entry_point(void *arg){ printf("Helloworld!n"); other_function(); printf("Helloagain?n"); returnNULL;}
int main(intargc, char **argv){ pthread_tthr; if(pthread_create(&thr, NULL, &entry_point,NULL)) { printf("Could not createthreadn"); return -1; }
if(pthread_join(thr, NULL)) { printf("Could not join threadn"); return -1; } return0;}In this example, note that "Helloagain?" is never printed. The thread exits in other_function andentry_point never returns. The argument to pthread_exit is a valueto be returned to the joining thread.SynchronizationThe pthreads specificationprovides many synchronization primitives; we will cover three inthis primer:• Barriers• Mutexes• SemaphoresBarriersSome parallel computations needto "meet up" at certain points before continuing. This can, ofcourse, be accomplished with semaphores, but another construct isoften more convenient: the barrier (the pthreads librarypthread_barrier_t). As a motivating example, take thisprogram:#define_XOPEN_SOURCE 600
#include#include#include
#define ROWS10000#define COLS10000#define THREADS10
doubleinitial_matrix[ROWS][COLS];doublefinal_matrix[ROWS][COLS];// Barriervariablepthread_barrier_tbarr;
extern voidDotProduct(int row, int col, doublesource[ROWS][COLS], doubledestination[ROWS][COLS]);extern doubledeterminant(double matrix[ROWS][COLS]);
void *entry_point(void *arg){ int rank =(int)arg; for(int row = rank* ROWS / THREADS; row < (rank + 1) * THREADS;++row) for(int col = 0; col < COLS;++col) DotProduct(row, col, initial_matrix, final_matrix);
// Synchronizationpoint int rc =pthread_barrier_wait(&barr); if(rc != 0&& rc != PTHREAD_BARRIER_SERIAL_THREAD) { printf("Could not wait onbarriern"); exit(-1); }
for(int row = rank* ROWS / THREADS; row < (rank + 1) * THREADS;++row) for(int col = 0; col < COLS;++col) DotProduct(row, col, final_matrix, initial_matrix);}
int main(intargc, char **argv){ pthread_tthr[THREADS];
// Barrierinitialization if(pthread_barrier_init(&barr, NULL, THREADS)) { printf("Could not create abarriern"); return -1; }
for(int i = 0; i< THREADS; ++i) { if(pthread_create(&thr[i], NULL,&entry_point, (void*)i)) { printf("Could not create thread %dn", i); return-1; } }
for(int i = 0; i< THREADS; ++i) { if(pthread_join(thr[i], NULL)) { printf("Could not join thread %dn", i); return-1; } }
double det =Determinant(initial_matrix); printf("Thedeterminant of M^4 = %fn", det);
return0;}This program spawns a number ofthreads, assigning each to compute part of a matrix multiplication.Each thread then uses the result of that computation in the nextphase: another matrix multiplication.There are a few things to notehere:1. The barrier declaration at thetop2. The barrier initialization inmain3. The point where each threadwaits for its peers to finish.NOTEThe preprocessor definition of_XOPEN_SOURCE at the top of the program is important; without it,the barrier prototypes are not defined in pthread.h. The definitionmust come before any headers are included.MutexesThe pthreads library provides abasic synchronization primitive: pthread_mutex_t. The declarationsrequired to use pthreads mutexes are included in pthread.h. This isa standard mutex with lock and unlock operations; see thisexample:#include#include#include
#defineITERATIONS 10000
// A sharedmutexpthread_mutex_tmutex;doubletarget;
void*opponent(void *arg){ for(int i = 0; i< ITERATIONS; ++i) { // Lock the mutex pthread_mutex_lock(&mutex); target -= target * 2 + tan(target); // Unlock the mutex pthread_mutex_unlock(&mutex); }
returnNULL;}
int main(intargc, char **argv){ pthread_tother;
target =5.0;
// Initialize themutex if(pthread_mutex_init(&mutex, NULL)) { printf("Unable to initialize amutexn"); return -1; }
if(pthread_create(&other, NULL, &opponent,NULL)) { printf("Unable to spawn threadn"); return -1; }

for(int i = 0; i< ITERATIONS; ++i) { pthread_mutex_lock(&mutex); target += target * 2 + tan(target); pthread_mutex_unlock(&mutex); }
if(pthread_join(other, NULL)) { printf("Could not join threadn"); return -1; }
// Clean up themutex pthread_mutex_destroy(&mutex);
printf("Result:%fn", target);
return0;}The important functions formanaging mutexes are:• pthread_mutex_init: Initializea new mutex.• pthread_mutex_destroy: Clean upa mutex that is no longer needed.• pthread_mutex_lock: Acquire amutex (blocking if it is not available).• pthread_mutex_unlock: Release amutex that you previously locked.SemaphoresThe pthreads library itself doesnot provide a semaphore; however, a separate POSIX standard doesdefine them. The necessary declarations to use these semaphores arecontained in semaphore.h.NOTE: Do not confuse these withSystemV semaphores which are in sys/sem.h.#include#include#include
#define THREADS20
sem_tOKToBuyMilk;intmilkAvailable;
void* buyer(void*arg){ // P() sem_wait(&OKToBuyMilk); if(!milkAvailable) { // Buy some milk ++milkAvailable; } // V() sem_post(&OKToBuyMilk);
returnNULL;}
int main(intargc, char **argv){ pthread_tthreads[THREADS];
milkAvailable =0;
// Initialize thesemaphore with a value of 1. // Note the secondargument: passing zero denotes // that thesemaphore is shared between threads (and // notprocesses). if(sem_init(&OKToBuyMilk, 0, 1)) { printf("Could not initialize asemaphoren"); return -1; }
for(int i = 0; i< THREADS; ++i) { if(pthread_create(&threads[i], NULL,&buyer, NULL)) { printf("Could not create thread %dn", i); return-1; } }
for(int i = 0; i< THREADS; ++i) { if(pthread_join(threads[i], NULL)) { printf("Could not join thread %dn", i); return-1; } }
sem_destroy(&OKToBuyMilk);
// Make sure wedon't have too much milk. printf("Total milk:%dn", milkAvailable);
return0;}The semaphore API has severalfunctions of note:• sem_init: Initialize a newsemaphore. Note, the second argument denotes how the semaphore willbe shared. Passing zero denotes that it will be shared amongthreadsrather than processes. The final argument is the initial value ofthe semaphore.• sem_destroy: Deallocate anexisting semaphore.• sem_wait: This is the P()operation.• sem_post: This is the V()operation.

  

爱华网本文地址 » http://www.aihuau.com/a/25101011/78061.html

更多阅读

的地得的用法 的和地的区别及用法

的地得的用法——简介日常工作中,常会有人提到“的”“地”“得”用法的问题,不少学生对“的、地、得”用法也是含糊不清,乱用一气,作业自然会在“的”“地”“得”用法上出错,并且屡改屡犯。大家都知道,“的”、“地”、“得”这三个字的

眼线膏的用法画出迷人眼线 美宝莲眼线膏

眼线膏的用法画出迷人眼线——简介美眉们一般都习惯用眼线笔来画眼线,今天小编要在这里教大家如何用眼线膏来描画眼线,步骤很简单,想要画好眼妆的美眉们,赶紧准备好工具,跟小编一起来学习吧!眼线膏的用法画出迷人眼线——工具/原料

护发素的用法 护发素发膜的正确用法

护发素的用法——简介护发素可以为头发提供一层保护,或许就因此得名了吧。比起洗发用品,护发素能够令头发看起来更自然和健康。 下面来介绍一下护发素的用法供参考。 护发素的用法——工具/原料护发素护发素的用法——方法/步骤护发

各种化妆刷的用法 如何使用彩妆

各种化妆刷的用法——简介来了解各种化妆刷的用法吧各种化妆刷的用法——方法/步骤各种化妆刷的用法 1、用平头眼影刷沾取少量眼影,从睫毛根部开始徐徐向上淡开,注意层次过渡均匀,刚开始训练以清淡为宜。(精选动物毛的扁平轻薄的刷头可

卫生棉条的用法 短导管卫生棉条的用法

卫生棉条的用法——简介卫生棉棉条,有称卫生栓,简称棉条,是一种棉质的圆柱体,在女性月经来潮时,可置入阴道中吸收经血。一个卫生棉条使用用者,一生中使用的卫生棉条可能超过10,000个。卫生棉条为众多女性提供了极大的便利,但是你知道卫生棉

声明:《pthread简单的用法 pthread exit 用法》为网友烟雨凡馨分享!如侵犯到您的合法权益请联系我们删除