weixin_54910555 2021-02-21 16:55 采纳率: 22.2%
浏览 34

问题: 为什么我的删除链表函数总是无法执行,我在主线程里插入了节点。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

typedef struct node
{
	int data;
	struct node *next;
}list;

pthread_mutex_t mutex;
list *p=NULL;

list *create(void)
{
	list *p=NULL;

	p=(list *)malloc(sizeof(list));
	if(p==NULL)
	{
		printf("create malloc is failed\n");
		return NULL;
	}

	p->data=0;
	p->next=NULL;
	return p;
}

int length_link_list(list *h)
{
	int len = 0;
	list *p = h->next;

	while(p != NULL){
		len++;
		p = p->next;
	}
	return len;
}

int instr_list(list *h,int pos,int data)
{
	int i=0;
	list *p=NULL;

	p=(list *)malloc(sizeof(list));
	if(p==NULL)
	{
		printf("instr_list malloc is falled\n");
		return -1;
	}

	for(i=1;i<pos;i++)
	{
		h=h->next;
	}

	h->data=data;

	p->next=h->next;
	h->next=p;

	return 0;
}

int delete_list(list *h,int pos)
{
	int i=0;
	list *p=NULL;
	if(pos<1 || pos>length_link_list(h))
	{
		printf("delete_any_node pos error\n");
		return -1;
	}
	for(i=1;i<pos;i++)
	{
		h=h->next;
	}

	p=h->next;
	h->next=p->next;
	free(p);
	return 0;
}

int fine_list(list *h,int data)
{
	int i=0;
	int pos=1;
	list *p=h->next;

	while(p!=NULL)
	{
		if(p->data==data)
		{
			printf("fine is\n");
		}
		pos++;
		p=p->next;
	}

	return pos;

}

int my_printf(list *h)
{
	list *p=h->next;
	while(p!=NULL)
	{
		printf("%d",p->data);
		p=p->next;
	}
	printf("\n");
	return 0;
}

void *Fun(void *arg)
{
	int pos=0;
	pthread_mutex_lock(&mutex);

	pos=fine_list(p,1);

	delete_list(p,pos);

	printf(" ------------\n");
	my_printf(p);

	pthread_mutex_unlock(&mutex);
	return NULL;
}

int main(int argc, const char *argv[])
{
	int ret=0;
	pthread_t pid;

	ret=pthread_mutex_init(&mutex,NULL);
	if(ret!=0)
	{
		printf("pthread_mutex_init is failed\n");
		return -1;
	}

	pthread_mutex_lock(&mutex);
	p=create();
	instr_list(p,1,0);
	instr_list(p,2,1);
	instr_list(p,3,2);
	pthread_mutex_unlock(&mutex);

	ret=pthread_create(&pid,NULL,Fun,NULL);
	if(ret!=0)
	{
		printf("pthread_create is failed\n");
		return -1;
	}

	pthread_join(pid,NULL);

	return 0;
}
stu@stu-VirtualBox:~/day5$ gcc xiancheng2.c -lpthread
stu@stu-VirtualBox:~/day5$ ./a.out
fine is
delete_any_node pos error
 ------------
120
stu@stu-VirtualBox:~/day5$ 

题目:主线程创建并插入链表节点,新线程查找节点,找到则删除该节点

问题:为什么我的删除链表函数总是无法执行,我在主线程里插入了节点,为什么在子线程里无法找得到,分配了内存在堆上,为什不共享,还有在主线程插入我的想法是应该是012,为什么是120,这是什么原因

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
    • ¥15 有赏,i卡绘世画不出
    • ¥15 如何用stata画出文献中常见的安慰剂检验图
    • ¥15 c语言链表结构体数据插入
    • ¥40 使用MATLAB解答线性代数问题
    • ¥15 COCOS的问题COCOS的问题
    • ¥15 FPGA-SRIO初始化失败
    • ¥15 MapReduce实现倒排索引失败
    • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
    • ¥15 找一位技术过硬的游戏pj程序员