linux c多线程编程实例代码

所属分类: 软件编程 / C 语言 阅读数: 103
收藏 0 赞 0 分享

直接看代码吧,代码里有注释

复制代码 代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#define MAX 3

int number =0;
pthread_t id[2];
pthread_mutex_t mut; //初始化静态互斥锁

void thread1(void)
{
    int i;
    printf("Hello,I am pthread1!\n");
    for (i=0; i<MAX; i++)
    {
        pthread_mutex_lock(&mut);  //此处上锁,保证number的唯一性
            number ++;  
            printf("Thread1:number = %d\n",number);
        pthread_mutex_unlock(&mut);
        sleep(1);  //linux c下 sleep(minute),里面变量单位是分钟
    }
    pthread_exit(NULL); //线程通过执行此函数,终止执行。返回是一个空指针类型
}

void thread2(void)
{
    int j;
    printf("Hello,I'm pthread2\n");
    for(j=0; j<MAX; j++)
    {
        pthread_mutex_lock(&mut);
             number ++;
             printf("Thread2:number = %d\n",number);
        pthread_mutex_unlock(&mut);
        sleep(1);
    }
    pthread_exit(NULL);
}

void thread_create(void)
{
    int temp;
    memset(&id, 0, sizeof(id));
if(temp = pthread_create(&id[0], NULL, (void *)thread1, NULL)!= 0)
                          //参数:线程标识符指针 线程属性  线程运行函数起始地址  运行函数属性
                          //创建成功返回 0
        printf("Thread 1 fail to create!\n");
    else
        printf("Thread 1 created\n");
    if(temp = pthread_create(&id[1], NULL, (void *)thread2, NULL)!= 0)
        printf("Thread 2 fail to create!\n");
    else
        printf("Thread 2 created!\n");
 }  
void thread_wait()
{
    if(id[0] != 0)
    {
        pthread_join(id[0], NULL); //等待线程结束,使用此函数对创建的线程资源回收
        printf("Thread1 completed!\n");
    }
    if(id[1] != 0)
    {
        pthread_join(id[1], NULL);
        printf("Thread2 completed!\n");
    }
}
int main(void)
{
int i,ret1,ret2;
pthread_mutex_init(&mut, NULL); //动态互斥锁
    printf("Main fuction,creating thread...\n");
    thread_create();
    printf("Main fuction, waiting for the pthread end!\n");
    thread_wait();
    return (0);
}

更多精彩内容其他人还在看

C++中四种对象生存期和作用域以及static的用法总结分析

以下是对C++中四种对象生存期和作用域以及static的用法进行了详细的介绍,需要的朋友可以过来参考下
收藏 0 赞 0 分享

C++嵌套类与局部类详细解析

从作用域的角度看,嵌套类被隐藏在外围类之中,该类名只能在外围类中使用。如果在外围类之外的作用域使用该类名时,需要加名字限定
收藏 0 赞 0 分享

C++空类详解

以下是对C++中的空类进行了详细的介绍,需要的朋友可以过来参考下
收藏 0 赞 0 分享

C++之友元:友元函数和友元类详解

友元是一种允许非类成员函数访问类的非公有成员的一种机制。可以把一个函数指定为类的友元,也可以把整个类指定为另一个类的友元
收藏 0 赞 0 分享

C++中返回指向函数的指针示例

int (*ff(int)) (int *,int);表示:ff(int)是一个函数,带有一个int型的形参,该函数返回int (*) (int *,int),它是一个指向函数的指针,所指向的函数返回int型并带有两个分别是Int*和int型的形参
收藏 0 赞 0 分享

C数据结构之单链表详细示例分析

以下是对C语言中的单链表进行了详细的分析介绍,需要的朋友可以过来参考下
收藏 0 赞 0 分享

C数据结构之双链表详细示例分析

以下是对c语言中的双链表进行了详细的分析介绍,需要的朋友可以过来参考下
收藏 0 赞 0 分享

浅析如何在c语言中调用Linux脚本

如何在c语言中调用Linux脚本呢?下面小编就为大家详细的介绍一下吧!需要的朋友可以过来参考下
收藏 0 赞 0 分享

深入解析unsigned int 和 int

以下是对unsigned int和int进行了详细的分析介绍,需要的朋友可以过来参考下
收藏 0 赞 0 分享

浅谈C++中的string 类型占几个字节

本篇文章小编并不是为大家讲解string类型的用法,而是讲解我个人比较好奇的问题,就是string 类型占几个字节
收藏 0 赞 0 分享
查看更多