pthread创建线程及遇到问题解决

出现的错误:invalid conversion from `void*' to `void*(*)(void*)

原来是定义的void reader_function();

pthread_create(&reader,NULL,(void*)&reader_function,NULL);

这样的代码用gcc编译不出问题,用gcc编译有问题。为了两者都没有问题,所以就改为了 void * reader_function();

这样改过之后,又出现了新的问题:invalid conversion from `void*(*)()' to `void*(*)(void*)'

这时又需要改变reader_function函数,给这个函数加上参数变为:void * reader_function(void*);

执行makefile时出现下面错误

undefined reference to `pthread_create'

要增加 -lpthread

gcc pthreadTest.cpp -o pthreadTest -lpthread



#include 
#include 
#include 
#include 

void* reader_function(void*args);
void writer_function();
pthread_mutex_t mutex;
int main(void) {
    puts("Hello World!!!");
    pthread_t reader;
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&reader,NULL,reader_function,NULL);
//    sleep(1);
    writer_function();
    return EXIT_SUCCESS;
}
void writer_function(){
    sleep(1);
    int i=0;
    while(1){

        printf("this is writer :%d\n",i);
        i++;
    }
}
void* reader_function(void * agrs){
    sleep(1);
    int i=0;
    while(1){

        printf("this is reader reader reader :%d\n",i);
        i++;
    }
    int *a = 0;
    return a;

}




使用互斥锁pthread_mutex_t,实现同一进程中,某些资源的同步。



#include 
#include 
#include 
#include 

void* reader_function(void*args);
void writer_function();
pthread_mutex_t mutex;
int tickets = 1000;
int main(void) {
    puts("Hello World!!!");
    pthread_t reader;
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&reader,NULL,reader_function,NULL);
//    sleep(1);
    writer_function();
    return EXIT_SUCCESS;
}
void writer_function(){

    while(1){
        pthread_mutex_lock(&mutex);
        if(tickets>0){
            printf("this is writer :%d\n",tickets--);
        }else{
            break;
        }
        pthread_mutex_unlock(&mutex);


    }
}
void* reader_function(void * agrs){
    while(1){
        pthread_mutex_lock(&mutex);
        if(tickets>0){
            printf("this is reader to sell tickets :%d\n",tickets--);
        }else{
            break;
        }
        pthread_mutex_unlock(&mutex);
    }
    int *a = 0;
    return a;
}


你可能感兴趣的:(Linux)