2012-05-04 151 views
-2

我正在制作一个多线程的C程序,它涉及在两个线程之间共享全局动态整数数组。一个线程将不断添加元素&另一个将独立扫描数组&释放扫描的元素。 任何一个可以建议我怎么能做到这一点,因为我做的是创造僵局 也请任何一个可以提供它的代码或解决这一僵局充分说明多线程和死锁

+6

不需要发布你的代码,所以我们可以帮你修复它。 – nos

+0

这个问题不能按原样回答。关。 – usr

+0

我还没有代码,我正处于分析的中间,因此我需要一些POC –

回答

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 
} 

这里是并行线程一个很好的例子/教程:*klick*

+0

你能解释一下吗 –

+0

它的一些有帮助我对你的答案有点帮助对我有帮助,但不完全是 –

1

在这样的情况下,你需要看看在阵列上的每个操作所产生的频率和负载。例如,如果数组正在被连续扫描,但每小时只能被添加一次,那么它的价值就在于找到一个非常缓慢,延迟大的写入机制,从而不需要读取锁定。在这种情况下,使用互斥锁锁定每个访问将非常令人不满。

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

Anohter事情ee不知道是失败的后果 - 如果新插入在实际插入之前排队了一段时间,或者它可能没有关系。

如果你想要'计算机科学101'的答案,很可能性能很差,请用互斥锁来锁定对阵列的每次访问。

+0

有多个线程可以写该全局数组,但只有一个线程来读取它,这个任务是连续的,我不确定哪个线程正在写什么时间或读线程读取哪个时间。 因此,为此我必须使用这种互斥或其他方法来完成此 –

+0

更多建议 –