繁体   English   中英

不知道互斥锁是否启动?

[英]Can't tell if Mutex Lock is kicking in or not?

我正在完成一项大学作业,并负责展示一个基本的互斥锁示例。 我从来没有使用过任何形式的线程,所以我是一个在 C++ 中使用 POSIX 线程的初学者。

我想让程序做的是创建 1000 个线程,将全局整数增加 1000。

#include        <iostream>
#include    <stdlib.h>
#include    <pthread.h>
#include    <sys/types.h>
#include    <unistd.h>
#include    <thread>

pthread_t   threadArr[1000];
pthread_mutex_t lock;

// Global int to increment
int numberToInc = 0;

void* incByTwo(void*)
{
    pthread_mutex_lock(&lock);
    for(int j = 0; j < 1000; j++){
        numberToInc += 1;
    }
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main()
{
    //Creates 1000 threads with incByTwo func
    for(int i = 0; i < 1000; i++){
        pthread_create(&threadArr[i], NULL, incByTwo, NULL);
    }


    std::cout << "\n" << numberToInc << "\n";

    

    return 0;
}

下面产生了一系列不同的结果,显然是因为线程是并发执行的,对吧?

现在,我已经通过插入让它正常工作

    for(int i = 0; i < 1000; i++){
        pthread_join(threadArr[i], NULL);
    }

在线程创建循环之后,然后删除互斥锁,它仍然有效。 我一直试图弄清楚 pthread_join 是如何工作的,但我有点迷茫。 有什么建议吗?

排序方式来显示互斥锁的作用。 因此,当我在函数中输出全局变量时,如果没有互斥锁,它有可能无序显示结果。

使用互斥锁运行数字范围,输出如下所示:

1000
2000
3000
... (etc)
10000

移除互斥锁后,输出的顺序可能会有所不同。

例如

1000
2000
4000
6000
3000
5000
7000
8000
9000
10000

虽然三个线程的最终结果是正确的,但顺序是乱序的。 在这个程序的上下文中,这并不重要,但我想如果它传递顺序不一致的值,它会把事情搞砸吗?

pthread_t   threadArr[10];
pthread_mutex_t lock;

int numberToInc = 0;


void* incByTwo(void*)
{

    pthread_mutex_lock(&lock);
    for(int j = 0; j < 1000; j++){
        numberToInc += 1;
    }

    std::cout << numberToInc << "\n";
    pthread_mutex_unlock(&lock); 
    return NULL;
}

int main()
{

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
            printf("\n mutex init failed\n");
            return 1;
        }

    for(int i = 0; i < 10; i++){
        pthread_create(&threadArr[i], NULL, incByTwo, NULL);
    }
    
    pthread_join(threadArr[0], NULL);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM