编程语言
首页 > 编程语言> > c++锁机制 demo1

c++锁机制 demo1

作者:互联网

int sum=0;
void* work1(void* argv)
{   
    int i=1;
    while(i<500)
    {
        sum+=i;
		i++;
    }
}
void* work2(void* argv)
{   
	int i=500;
    while(i<=1000)
    {
        sum+=i;
		i++;
    }
}
int fun() {
	int ans = 0;
	for (int i = 1; i <= 1000; i++) {
		ans += i;
	}
	return ans;
}
int main(void)
{
	locker m_mutex;
    cond m_cond;
	pthread_t tid1,tid2;
    pthread_create(&tid1, NULL, work1, NULL);
    pthread_create(&tid2, NULL, work2, NULL);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	cout<<sum<<endl;
	cout<<fun()<<endl;
    return 0;
}

在这里插入图片描述
这个例子主要说明线程的并发执行,我们创建了两个线程,但是使用了共享变量sum,所以可能执行一个线程一会他就去执行另外一个线程,另外一个线程之前也执行了一段时间了,它本身有一个值,但是由于是共享变量从另外一个线程切换到这个线程的时候就会把这个线程的值覆盖掉,所以用两个线程计算的sum永远小于fun函数最后计算出来的值。

然后我们加上锁试试。
在这里插入图片描述
结果就会一样。

#include <iostream>
#include <exception>
#include <pthread.h>
#include <semaphore.h>
#include <pthread.h>
using namespace std;
class locker
{
public:
    locker()
    {
        if (pthread_mutex_init(&m_mutex, NULL) != 0)
        {
            throw std::exception();
        }
    }
    ~locker()
    {
        pthread_mutex_destroy(&m_mutex);
    }
    bool lock()
    {
        return pthread_mutex_lock(&m_mutex) == 0;
    }
    bool unlock()
    {
        return pthread_mutex_unlock(&m_mutex) == 0;
    }
    pthread_mutex_t *get()
    {
        return &m_mutex;
    }

private:
    pthread_mutex_t m_mutex;
};

int sum=0;
locker m_mutex;
void* work1(void* argv)
{   
    int i=0;
    while(i<500)
    {
		m_mutex.lock();
        sum+=i;
		m_mutex.unlock();
		i++;
    }
}
void* work2(void* argv)
{   
	int i=500;
    while(i<=1000)
    {
		m_mutex.lock();
        sum+=i;
		m_mutex.unlock();
		i++;
    }
}
int fun() {
	int ans = 0;
	for (int i = 1; i <= 1000; i++) {
		ans += i;
	}
	return ans;
}
int main(void)
{
	pthread_t tid1,tid2;
    pthread_create(&tid1, NULL, work1, NULL);
    pthread_create(&tid2, NULL, work2, NULL);
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);
	cout<<sum<<endl;
	cout<<fun()<<endl;
    // m_mutex.lock();
    // work1(sum);
    // m_mutex.unlock();
    return 0;
}

标签:int,void,c++,demo1,mutex,pthread,线程,机制,NULL
来源: https://blog.csdn.net/zhazhali_fenqi/article/details/121478082