谁帮本人看下这多线程错在哪里

C语言 码拜 8年前 (2016-04-07) 801次浏览
struct mystruct
{
int *p;//传递线程的头
int intel;//长度
int sum;//需要查找的值
int id;//编号
};
void lens(void *pd)
{
struct mystruct *ps = pd;
for (int *pi = ps->p; pi < ps->p + ps->intel; pi++)
{
if (*pi == ps->sum)
{
printf(“线程%d已经找到值%d,地址为%p\n”, ps->id,*pi,pi);
return;
}
}
printf(“线程%d查找结束,未找到!\n”, ps->id);
}
void main()
{
int sum = 0;
char array[100] = { 0 };
time_t ts;
unsigned int times = time(&ts);
srand(times);
for (int i = 0; i < 100; i++)
{
array[i] = rand() % 100;
}
for (int i = 0; i < 100; i++)
{
printf(“%3d”, array[i]);
if ((i + 1) % 10 == 0)
{
printf(“\n”);
}
}
scanf(“%d”, &sum);
struct mystruct xc[10];
for (int i = 0; i < 10; i++)
{
xc[i].p = array + 10 * i;
xc[i].intel = 10;
xc[i].id = i;
xc[i].sum = sum;
_beginthread(lens, 0, &xc[i]);
}
system(“pause”);
}
谁帮本人看看着程序错在哪里 printf(“线程%d已经找到值%d,地址为%p\n”, ps->id,*pi,pi); 输出的时候只有第8个线程找到,这是什么情况!
解决方案

15

仔细看了一下,char array[100] = { 0 };这句替换成int array[100];,不然你的指针就乱了

30

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<process.h>
struct mystruct
{
	int *p;//传递线程的头
	int intel;//长度
	int sum;//需要查找的值
	int id;//编号
};
void lens(void *pd)
{
	struct mystruct *ps = (struct mystruct *)pd;
	for (int *pi = ps->p; pi < ps->p + ps->intel; pi++)
	{
		if (*pi == ps->sum)
		{
			printf("线程%d已经找到值%d,地址为%p\n", ps->id, *pi, pi);
			return;
		}
	}
	printf("线程%d查找结束,未找到!\n", ps->id);
}
void main()
{
	int sum = 0;
	int array[100] = { 0 };
	time_t ts;
	unsigned int times = time(&ts);
	srand(times);
	for (int i = 0; i < 100; i++)
	{
		array[i] = rand() % 100;
	}
	for (int i = 0; i < 100; i++)
	{
		printf("%3d", array[i]);
		if ((i + 1) % 10 == 0)
		{
			printf("\n");
		}
	}
	scanf("%d", &sum);
	struct mystruct xc[10];
	for (int i = 0; i < 10; i++)
	{
		xc[i].p = array + 10 * i;
		xc[i].intel = 10;
		xc[i].id = i;
		xc[i].sum = sum;
		_beginthread(lens, 0, &xc[i]);
	}
	system("pause");
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明谁帮本人看下这多线程错在哪里
喜欢 (0)
[1034331897@qq.com]
分享 (0)