带C的互斥线程
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带C的互斥线程相关的知识,希望对你有一定的参考价值。
These are the basic commands to use Mutex Threads in C
#include <pthread.h> //this is our lock and we use it to lock and unlock our mutex when shared data is accessed. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER //the signature of the thread function always looks like this. void* thread_function(void* arg) { //before accessing the shared resource pthread_mutex_lock(&lock); //do something access your shared resource pthread_mutex_unlock(&lock); pthread_exit(NULL); } //creating and calling threads int main() { pthread_t threads[3]; pthread_create(threads[0], NULL, &thread_function, void *arg); pthread_create(threads[1], NULL, &thread_function, void *arg); pthread_create(threads[2], NULL, &thread_function, void *arg); //join the threads, join call waits for all threads to finish int i; for(i = 0; i < 3; i++) { pthread_join(threads[i], NULL); } //after you are finish you should always destroy the thread pthread_mutex_destory(&lock); }
以上是关于带C的互斥线程的主要内容,如果未能解决你的问题,请参考以下文章