gpt4 book ai didi

C 多线程 : Race condition scenarios

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:15 26 4
gpt4 key购买 nike

在下面的代码中,我只是想看看我是否能够从每个线程将一个元素插入到数组中。它按预期工作。但后来我想知道,在什么情况下这里会出现竞争条件。我真的需要 volatile 还是信号量?我尝试删除信号量和 volatile 关键字,但它仍然有效。我也想在这里引发并查看竞争条件场景。同样,我可以从每个线程创建一个节点并将所有节点放入链表吗?这些都是想象中的场景..!!

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include "small_appl.h"

void * thread_func(void * arg);

int itr=0;
volatile int idx=0; //array index variable
sem_t sem1;
int arr_th[5]; //array where each thread will insert an element

int func_pointed(int a,int num_t)
{
pthread_t arr_thr[num_t];
int iter;
//create threads
for(iter=0;iter<num_t;iter++)
{
pthread_create(&arr_thr[iter],NULL,thread_func,(void *)a);
}

for (iter=0;iter<num_t;iter++)
{
pthread_join(arr_thr[iter],NULL);
}
}

int main(void)
{
int ip1=5,ip2=10,rev;

rev=sem_init(&sem1,0,0);
s_type dev_s={
.f_ptr=func_pointed,
.str="Diwakar",
.val=5
};

//initialize semaphore to 1
sem_post(&sem1);

func_aux(ip1,dev_s);

for(rev=0;rev<5;rev++)
{
printf("array : %d ",arr_th[rev]);
}

}

void * thread_func(void * arg)
{
sem_wait(&sem1);
printf("Got sema\n");
arr_th[idx]=itr;
idx++; itr++;
printf("Releasing sema\n");
sem_post(&sem1);

sleep(5);
}

最佳答案

要创建或模拟一个线程覆盖另一个线程完成的工作的情况,然后移除信号量并有策略地放置 sleep ,如:

void * thread_func(void * arg)
{
//sem_wait(&sem1);
//printf("Got sema\n");
arr_th[idx]=itr;
// print arr_th[idx]
sleep(5); <<== gives the threads more of a chance to wipe-out each other
// print arr_th[idx]
idx++; itr++;
//printf("Releasing sema\n");
//sem_post(&sem1);

sleep(5);
}

您可以添加一些明确突出问题的printf 语句。

volatile 告诉编译器不要删除未使用或至少看起来未使用的变量。

您可以从多个线程更新链接列表,但您必须序列化更新列表中链接(下一个和/或上一个)的代码的关键部分。

在 Windows XP 和更高版本中,CRT 是线程安全的,因此每个线程都可以发出 malloc()printf 等,而不必围绕这些调用序列化线程.

关于C 多线程 : Race condition scenarios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com