我正在制作一个多线程的C程序,它涉及在两个线程之间共享全局动态整数数组。一个线程将不断添加元素&另一个将独立扫描数组&释放扫描的元素。 任何一个可以建议我怎么能做到这一点,因为我做的是创造僵局 也请任何一个可以提供它的代码或解决这一僵局充分说明多线程和死锁
多线程和死锁
回答
对于线程的方式方法我会使用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*
你能解释一下吗 –
它的一些有帮助我对你的答案有点帮助对我有帮助,但不完全是 –
在这样的情况下,你需要看看在阵列上的每个操作所产生的频率和负载。例如,如果数组正在被连续扫描,但每小时只能被添加一次,那么它的价值就在于找到一个非常缓慢,延迟大的写入机制,从而不需要读取锁定。在这种情况下,使用互斥锁锁定每个访问将非常令人不满。
如果没有“扫描”操作的详细信息,尤其是持续时间和频率,建议采用线程通信策略以获得良好性能是不可能的。
Anohter事情ee不知道是失败的后果 - 如果新插入在实际插入之前排队了一段时间,或者它可能没有关系。
如果你想要'计算机科学101'的答案,很可能性能很差,请用互斥锁来锁定对阵列的每次访问。
有多个线程可以写该全局数组,但只有一个线程来读取它,这个任务是连续的,我不确定哪个线程正在写什么时间或读线程读取哪个时间。 因此,为此我必须使用这种互斥或其他方法来完成此 –
更多建议 –
- 1. 多线程死锁
- 2. 多线程中的死锁
- 3. Python线程和锁定:死锁
- 4. Ruby线程死锁
- 5. C#线程死锁
- 6. C++线程死锁
- 7. Python线程死锁
- 8. Delphi线程死锁
- 9. Java,线程死锁?
- 10. Java线程死锁
- 11. 寻找多线程死锁的原因?
- 12. SQL Server插入多个线程死锁
- 13. Java中的多线程死锁
- 14. FFMPEG:多线程解码死锁?
- 15. Java中的多线程死锁
- 16. 单存储过程和多线程的死锁
- 17. 产卵线程时死锁?
- 18. c3po助手线程死锁
- 19. MemoryStream.CopyTo()导致线程死锁
- 20. 死锁在Python线程
- 21. 线程死锁异步
- 22. 死锁的线程java
- 23. 线程池死锁与Task.Result
- 24. 死锁线程检查
- 25. 在C自制线程池的多线程死锁#
- 26. C多线程死锁的线程事件
- 27. 死锁和线程之前\或回报是死
- 28. 多线程和互斥锁
- 29. 两个线程程序防止死锁
- 30. Python的子流程-POPEN死锁在多线程环境中
不需要发布你的代码,所以我们可以帮你修复它。 – nos
这个问题不能按原样回答。关。 – usr
我还没有代码,我正处于分析的中间,因此我需要一些POC –