Skip to content

Instantly share code, notes, and snippets.

@wgm89
Last active December 17, 2015 01:49
Show Gist options
  • Save wgm89/5531475 to your computer and use it in GitHub Desktop.
Save wgm89/5531475 to your computer and use it in GitHub Desktop.
c thread
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#define MAX 100000000
pthread_t thread[2];
pthread_mutex_t mut;
void *thread1()
{
int numberone=0;
int i;
printf ("thread1 : I'm thread 1\n");
for (i = 0; i < MAX; i++)
{
//pthread_mutex_lock(&mut);
numberone++;
//pthread_mutex_unlock(&mut);
}
pthread_exit(NULL);
}
void *thread2()
{
int numbertwo=0;
int i;
printf("thread2 : I'm thread 2\n");
for (i = 0; i < MAX; i++)
{
numbertwo++;
}
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
/*创建线程*/
if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0)
printf("线程1创建失败!\n");
else
printf("线程1被创建\n");
if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0)
printf("线程2创建失败");
else
printf("线程2被创建\n");
}
void thread_wait(void)
{
/*等待线程结束*/
if(thread[0] !=0) {
pthread_join(thread[0],NULL);
printf("线程1已经结束\n");
}
if(thread[1] !=0) {
pthread_join(thread[1],NULL);
printf("线程2已经结束\n");
}
}
int main()
{
struct timeval starttime,endtime;
gettimeofday(&starttime,NULL);
/*用默认属性初始化互斥锁*/
pthread_mutex_init(&mut,NULL);
printf("主函数\n");
thread_create();
thread_wait();
gettimeofday(&endtime,NULL);
int timeuse = 1000000 * (endtime.tv_sec -starttime.tv_sec) + endtime.tv_usec - starttime.tv_usec;
printf("总共时间:%d",timeuse);
return 0;
}
➜ cl ./function
thread1 : I'm thread 1
thread2 : I'm thread 2
总共时间:399066 ➜ cl gcc thread.c -lpthread -o thread
➜ cl ./thread
主函数
线程1被创建
线程2被创建
thread1 : I'm thread 1
thread2 : I'm thread 2
线程1已经结束
线程2已经结束
总共时间:221633
numberone,numbertwo 定义为global 时:
主函数
线程1被创建
线程2被创建
thread1 : I'm thread 1
thread2 : I'm thread 2
线程1已经结束
线程2已经结束
总共时间:722538
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment