POSIX 自旋锁(pthread_spin_lock)的一个例子

本文展示了一个使用pthread_spin_lock进行线程同步的C语言示例。通过两个线程分别增加和减少共享变量,演示了如何防止数据竞争,确保线程安全。程序详细展示了线程创建、同步锁的使用及线程结束后的资源回收。

发现网上的可以跑的简单demo好少,给出一个以备不时之需哈

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static pthread_spinlock_t spinlock;
static int test_value = 0;

int UDP_first_thread() 
{
	int i ,ret;
	
	printf("UDP_first_thread begin\n");
	for(i =0 ;i<10 ;i++ ) {
	pthread_spin_lock(&spinlock);
		test_value++;
		printf("test_value %d\n", test_value);
		sleep(5);
		pthread_spin_unlock(&spinlock);
	}
	printf("UDP_first_thread end\n");
	return ret;
}

int UDP_second_thread() 
{
	int i ,ret;
	
	printf("UDP_second_thread begin\n");
	for(i =0 ;i<10 ;i++ ) {
	pthread_spin_lock(&spinlock);
		test_value--;
		printf("test_value %d\n", test_value);
		sleep(3);
		pthread_spin_unlock(&spinlock);
	}
	printf("UDP_second_thread end\n");
	return ret;
}

int main(int argC, char* arg[]) 
{

	int err;
	pthread_t tid1, tid2;
	
	pthread_spin_init(&spinlock,0);
	//----------------创建UDP服务端线程----------------
	err = pthread_create(&tid1, NULL, UDP_first_thread, NULL);
	if (err != 0) {
		perror(" fail to create thread ");
		return -1;
	}
	sleep(1);
	
		err = pthread_create(&tid1, NULL, UDP_second_thread, NULL);
	if (err != 0) {
		perror(" fail to create thread ");
		return -1;
	}
   
    pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);
	
	printf("main end\n");

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值