-2

我正在制作一个多线程 C 程序,其中涉及在两个线程之间共享全局动态整数数组。一个线程将继续向其中添加元素,另一个线程将独立扫描数组并释放扫描的元素。任何人都可以建议我如何做到这一点,因为我正在做的是造成死锁 请任何人都可以提供它的代码或解决这个死锁的方法并提供完整的解释

4

3 回答 3

1

对于线程,我会使用 pthread。用 编译它-pthread

#include <pthread.h>

int *array;

// return and argument should be `void *` for pthread
void *addfunction(void *p) {
    // add to array
}

// same with this thread
void *scanfunction(void *p) {
    // scan in array
}

int main(void) {
    // pthread_t variable needed for pthread
    pthread_t addfunction_t, scanfunction_t; // names are not important but use the same for pthread_create() and pthread_join()
    // start the threads
    pthread_create(&addfunction_t, NULL, addfunction, NULL); // the third argument is the function you want to call in this case addfunction()
    pthread_create(&scanfunction_t, NULL, scanfunction, NULL); // same for scanfunction()
    // wait until the threads are finish leave out to continue while threads are running
    pthread_join(addfunction_t, NULL);
    pthread_join(scanfunction_t, NULL);
    // code after pthread_join will executed if threads aren't running anymore
}

这是 pthread 的一个很好的示例/教程:*klick*

于 2012-05-04T11:11:35.613 回答
1

在这种情况下,您需要查看数组上每个操作产生的频率和负载。例如,如果阵列被连续扫描,但每小时只添加一次,那么找到一种非常缓慢、延迟缠身的写入机制来消除对读取锁的需求是值得的。在这种情况下,用互斥锁锁定每个访问将是非常不令人满意的。

如果没有“扫描”操作的详细信息,尤其是持续时间和频率,就不可能建议一种线程通信策略以获得良好的性能。

另一个你不知道的事情是失败的后果——新添加的内容在实际插入之前是否排队一段时间可能并不重要,或者它可能。

如果您想要一个“计算机科学 101”的答案,而且很可能性能很差,请使用互斥锁锁定对数组的每次访问。

于 2012-05-04T12:29:29.867 回答
0

http://www.liblfds.org

版本 6 包含一个无锁队列。

为 Windows 和 Linux 开箱即用地编译。

于 2012-05-04T14:52:19.060 回答