通过创建两个线程来实现对一个数的递加。
或许这个实例没有实际运用的价值,但是稍微改动一下,我们就可以用到其他地方去拉。
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#define MAX 10
pthread_t thread[2];
pthread_mutex_t mut;
int number=0, i;
void *thread1(void *)
{
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 :the main function is waiting for me?\n");
pthread_exit(NULL);
}
void *thread2(void *)
{
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 :the main function is waiting for me? \n");
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread)); //comment1
/*Create thread*/
if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0) //comment2
printf("Thread 1 fail to create!\n");
else
printf("Thread 1 created!\n");
if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0) //comment3
printf("Thread 2 fail to create!");
else
printf("Thread 2 created!\n");
}
void thread_wait(void)
{
/*Wait thread end*/
if(thread[0] !=0) { //comment4
pthread_join(thread[0],NULL);
printf("Thread 1 completed\n");
}
if(thread[1] !=0) { //comment5
pthread_join(thread[1],NULL);
printf("Thread 2 completed.\n");
}
}
int main()
{
/*init mutex*/
pthread_mutex_init(&mut,NULL);
printf("Main function,creating thread...\n");
thread_create();
printf("Main function,waiting for thread end....\n");
thread_wait();
return 0;
}
下面是运行结果:
- 大小: 13.3 KB
分享到:
相关推荐
线程如何去创建 ,多线程如何控制输出!互斥控制!
三个多线程经典代码只需要5分 转别人的,没分下载了 混点分,请多多支持
linux下C语言多线程编程实例.pdf
linux下C语言多线程编程实例.docx
linux下C语言多线程编程实例.doc
linux下C语言多线程编程实例[归纳].pdf
linux c 开发中多线程的典型实例,可在linux平台直接运行,通过实践熟悉理解多线程工作原理。
linux下C语言多线程编程实例 在单线程的程序里,有两种基本的数据:全局变量和局部变量。但在多线程程序里,还有第三种数据类型:线程数据(TSD: Thread-Specific Data)
linux下的C\C++多进程多线程编程实例详解 1、多进程编程 #include #include #include <unistd> int main() { pid_t child_pid; /* 创建一个子进程 */ child_pid = fork(); if(child_pid == 0) { printf...
主要介绍了linux系统中的c多线程编程实例,大家可以参考使用以下代码
在Linux下, 线程的互斥量数据类型是pthread_mutex_t. 在使用前, 要对它进行初始化: 对于静态分配的互斥量, 可以把它设置为PTHREAD_MUTEX_INITIALIZER, 或者调用pthread_mutex_init. 对于动态分配的互斥量, 在申请...
18、Linux网络编程18——tcp并发服务器(多线程) 19、Linux网络编程——tcp高效并发服务器(select实现) 20、Linux网络编程——tcp高效并发服务器(poll实现) 21、Linux网络编程——tcp高效并发服务器(epoll实现...
Linux下基于C/C++的Socket的阻塞和异步编程实例