在本章中,我们将学习:
1. API’在pthread互斥锁中使用的
2.示例1
3.示例2
1.要初始化互斥锁,请使用以下API:
int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
互斥锁的属性可以通过互斥锁指定,使用NULL可以使用默认属性。
2.要锁定关键部分,请使用以下API。这是一个阻止呼叫。这意味着它将阻塞调用线程,直到获得锁为止。
int pthread_mutex_lock(pthread_mutex_t *mutex)
3.要获得对关键部分的锁定而不阻止使用以下API,请执行以下操作:
int pthread_mutex_trylock(pthread_mutex_t *mutex);
4.要解锁互斥锁,请使用以下API:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
在使用互斥锁之前,让我们看一下没有线程同步的以下函数的输出:
范例1:
在下面的程序中,我创建了2个线程,两个线程都尝试增加计数器。这称为竞争条件。这意味着有2个线程在竞速以增加计数。
发生竞争状况的部分称为关键部分。
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <pthread.h> //for more tutorials 上 C, C ++, STL, DS, Linux visit www.ProDeveloperTutorial.com int counter = 0; void *myFun() { counter++; printf("Counter value: %d\n",counter); } int main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, NULL, &myFun, NULL)) ) { printf("Thread creation failed: %d\n", rc1); } if( (rc2=pthread_create( &thread2, NULL, &myFun, NULL)) ) { printf("Thread creation failed: %d\n", rc2); } pthread_join( thread1, NULL); pthread_join( thread2, NULL); return 0; }
输出:
Counter value: 1 Counter value: 1
因此,从输出中可以看到,两种情况下的计数器值为1。
因此,为避免此类错误,我们使用互斥锁和解锁。
范例2:
在下面的示例中,我使用了互斥锁和互斥锁。
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <pthread.h> //for more tutorials 上 C, C ++, STL, DS, Linux visit www.ProDeveloperTutorial.com int counter = 0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void *myFun() { pthread_mutex_lock( &mutex1 ); counter++; printf("Counter value: %d\n",counter); pthread_mutex_unlock( &mutex1 ); } int main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, NULL, &myFun, NULL)) ) { printf("Thread creation failed: %d\n", rc1); } if( (rc2=pthread_create( &thread2, NULL, &myFun, NULL)) ) { printf("Thread creation failed: %d\n", rc2); } pthread_join( thread1, NULL); pthread_join( thread2, NULL); return 0; }
输出:
Counter value: 1 Counter value: 2
从上面的输出中可以看到,该值将始终返回2。
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |