#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
char *message1 = "Thread 1";
char *message2 = "Thread 2";
int iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* Wait till threads are complete before main continues. Unless we */
/* wait we run the risk of executing an exit which will terminate */
/* the process and all threads before the threads have completed. */
pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
exit(0);
}
void *print_message_function( void *ptr )
{
char *message;
int i;
for(i = 0; i < 100000; i++)
{
message = (char *) ptr;
usleep(1000);
printf("%s \t\t %d\n", message, i);
}
}
编译和运行程序
2073 gcc -lpthread muti-thread.c
2074 ./a.out
在另外一个putty终端上运行
root@9131-TestMAC-Compile:/home/tjiang/code/join# ps -eLF | grep a.out
root 6162 5743 6162 0 3 4567 532 0 14:46 pts/4 00:00:00 ./a.outroot 6162 5743 6163 0 3 4567 532 1 14:46 pts/4 00:00:00 ./a.out
root 6162 5743 6164 0 3 4567 532 1 14:46 pts/4 00:00:00 ./a.out
root 6172 6103 6172 0 1 836 844 1 14:47 pts/0 00:00:00 grep --color=auto a.out
其实在Linux中,新建的线程并不是在原先的进程中,而是系统通过一个系统调用clone()。该系统copy了一个和原先进程完全一样的进程,并在这个进程中执行线程函数。不过这个copy过程和fork不一样。 copy后的进程和原先的进程共享了所有的变量,运行环境。这样,原先进程中的变量变动在copy后的进程中便能体现出来。

本文展示了一个简单的Linux多线程程序示例,通过创建两个线程并让它们执行相同的功能来演示线程间的同步与资源共享。文章还介绍了如何使用pthread库进行线程创建与管理。

1624

被折叠的 条评论
为什么被折叠?



