代码拉取完成,页面将自动刷新
/*
* =========================================================================
*
* FileName: a.c
*
* Description:
*
* Version: 1.0
* Created: 2021-08-09 23:14:10
* Last Modified: 2021-08-09 23:15:26
* Revision: none
* Compiler: gcc
*
* Author: zt ()
* Organization:
*
* =========================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int counter = 0;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
void* doit ( void* )
{
int i, val;
for ( i = 0; i < 5000; i++ )
{
pthread_mutex_lock ( &g_mutex );
pthread_mutex_lock ( &g_mutex );
val = counter;
printf ( "%x: %d\n", pthread_self(), val + 1 );
counter = val + 1;
pthread_mutex_unlock ( &g_mutex );
pthread_mutex_unlock ( &g_mutex );
}
return NULL;
}
int main ( int argc, char* argv[] )
{
( void ) argc;
( void ) argv;
pthread_t tid1, tid2;
pthread_create ( &tid1, NULL, doit, NULL );
pthread_create ( &tid2, NULL, doit, NULL );
pthread_join ( tid1, NULL );
pthread_join ( tid2, NULL );
return 0;
}
//结果:加1次锁,可以正确的输出1~10000;加2次锁,死锁,不输出任何信息。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。