[从一个空列表开始,我需要同时运行两个线程才能在C的同一列表中分别插入100万个随机整数。我试图将空列表传递给正在创建的线程。该功能似乎无法识别以前创建的列表。我相信这是因为我错了。错误如下:
错误:未声明“ my_list”(此功能的首次使用);您是说“ va_list”吗?List_Insert(&my_list,32);
任何建议都将不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
//basic node structure
typedef struct __node_t {
int key;
struct __node_t *next;
} node_t;
//basic list structure (one used per list)
typedef struct __list_t {
node_t *head;
pthread_mutex_t lock;
} list_t;
void List_Init(list_t *L) {
L->head = NULL;
pthread_mutex_init(&L->lock, NULL);
}
int List_Insert(list_t *L, int key) {
pthread_mutex_lock(&L->lock);
node_t *new = malloc(sizeof(node_t));
if (new == NULL) {
perror("malloc");
pthread_mutex_unlock(&L->lock);
return -1; //fail
}
new->key = key;
new->next = L->head;
L->head = new;
pthread_mutex_unlock(&L->lock);
return 0; //success
}
int List_Lookup(list_t *L, int key) {
pthread_mutex_lock(&L->lock);
node_t *curr = L->head;
while (curr) {
if (curr->key == key) {
pthread_mutex_unlock(&L->lock);
return 0; //success
}
curr = curr->next;
}
pthread_mutex_unlock(&L->lock);
return -1; //failure
}
//Ensures function executes after main
void *myThread(void *vargp) __attribute__((destructor));
int main(int argc, char *argv[]){
//Define an empty list
list_t my_list;
//Initialize the list
List_Init(&my_list);
//Create the threads
int i;
pthread_t tid;
for (i = 0; i < 2; i++)
pthread_create(&tid, NULL, myThread, (void *)&my_list);
pthread_exit(NULL);
return 0;
}
//Function to be executed by both threads
void *myThread(void *vargp)
{
////FUNCTION NOT RECOGNIZING PREVIOUSLY CREATED LIST////
printf("Inserting into list\n");
List_Insert(&my_list, 32);
}
Well,my_list
是在main
范围内声明的变量。因此在myThread
函数内部不可见。您只需使用vargp
参数即可实现此目的:
void *myThread(void *vargp)
{
list_t *my_list = (list_t *)vargp;
printf("Inserting into list\n");
List_Insert(my_list, 32);
// Notice the missing & in the call!
}
[另一个问题是该列表分配在main()
函数的堆栈框架内。这意味着在主返回之后,该堆栈框架将不再可用,并且您将具有不确定的行为。您在这里有2个选项:
都可以使用malloc
等待main
函数中的所有线程,因此当您的线程使用该列表时,main
的堆栈帧保持活动状态。
线程功能中没有my_list
。从main传递my_list
后,您可以通过本地变量vargp
(现在是“ my_list”)访问它]