#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,这是什么原因