C 多线程学习

来源:互联网 发布:小米电视有线网络ip 编辑:程序博客网 时间:2024/05/18 00:23

   用vi编辑c的多线程时用gcc ThreadTest_1.c 编译时 一直报错,报错如下:

/tmp/ccgkO5iU.o:在函数‘thread_create’中:
ThreadTest_1.c:(.text+0x13b):对‘pthread_create’未定义的引用
ThreadTest_1.c:(.text+0x15e):对‘pthread_create’未定义的引用
/tmp/ccgkO5iU.o:在函数‘thread_wait’中:
ThreadTest_1.c:(.text+0x182):对‘pthread_join’未定义的引用
ThreadTest_1.c:(.text+0x1a0):对‘pthread_join’未定义的引用

查了一些博客终于解决了,原因是pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,

现将源码如下:

#include <pthread.h>

#include <stdio.h>
#define MAX 10
 
pthread_t thread[2];
pthread_mutex_t mut;
int number  = 0,i;

void *thread1()
{   
    printf("thread1 : I'm thread 1\n");
   
    for(i = 0; i< MAX; i++)
    {
        printf("thread1: number = %d\n",number);
        pthread_mutex_lock(&mut);
        number++;
        pthread_mutex_unlock(&mut);
        sleep(2);
    }
    printf("thread1: 主函数在等我们完成任务吗?\n");
    pthread_exit(NULL);
}   

void *thread2()
{
    printf("thread2 : I'm thread 2\n");
    for(i = 0;i < MAX; i++)
    {
        printf("thread2 : number = %d\n",number);
        pthread_mutex_lock(&mut);
        number++;
        pthread_mutex_unlock(&mut);
        sleep(3);
    }   

    printf("thread2:主函数在等我们完成任务吗?\n");
    pthread_exit(NULL);
}

void thread_create(void)
{
    pthread_create(&thread[0],NULL,thread1,NULL);
    printf("线程1被创建\n");
    pthread_create(&thread[1],NULL,thread2,NULL);
    printf("线程2被创建\n");
}

void thread_wait(void)
{
    /*等待线程结束*/
    pthread_join(thread[0],NULL);
    printf("线程1已经结束\n");
    pthread_join(thread[1],NULL);
    printf("线程2已经结束\n");
}

int main()
{
    printf("我是主函数偶,我正在创建线程,呵呵\n");

    /*用默认属性初始化互斥锁*/
    pthread_mutex_init(&mut,NULL);
    printf("我是主函数偶,我正在创建线程,呵呵\n");
    thread_create();
    printf("我是主函数,我正在等待线程完成任务\n");
    thread_wait();
    return 0;
}

执行命令如下:gcc -o pthread -lpthread ThreadTest_1.c
./pthread

执行完毕

执行结果:

我是主函数偶,我正在创建线程,呵呵
我是主函数偶,我正在创建线程,呵呵
线程1被创建
线程2被创建
我是主函数,我正在等待线程完成任务
thread2 : I'm thread 2
thread2 : number = 0
thread1 : I'm thread 1
thread1: number = 1
thread1: number = 2
thread2 : number = 3
thread1: number = 4
thread2 : number = 5
thread1: number = 6
thread1: number = 7
thread2 : number = 8
thread1: number = 9
thread2 : number = 10
thread1: 主函数在等我们完成任务吗?
线程1已经结束
thread2:主函数在等我们完成任务吗?
线程2已经结束


如果还是不能执行,就再引入一句

 #pragma comment(lib, "pthreadVC2.lib")

0 0