日期:2014-05-16  浏览次数:20777 次

代码示例:linux多线程
#include <stdio.h>
#include <pthread.h>
#include <sys/syscall.h>

int gettid(){
	return syscall(SYS_gettid);
}

void print_pid_tid(){
	printf("Current pid is %u and current tid(lwp_id) is %u\n", 
		(unsigned int)getpid(), (unsigned int)gettid());
}
void * thread_func(){
	printf("Created thread: ");
	print_pid_tid();
}

int main(){
	pthread_t  thread; 
	int err = pthread_create(&thread, NULL, thread_func, NULL); //第3个参数是一个函数,相当于java Runnable类里的run方法
	if(err != 0){
		perror("Cannot create thread");
	}

	pthread_join(thread, NULL); //跟java里的Thread.join()方法一码事
	printf("Main thread: ");
	print_pid_tid();
}


	



编译时要使用-pthread参数
$gcc -pthread fullthread.c



运行结果
Created thread: Current pid is 29739 and current tid(lwp_id) is 29740
Main thread: Current pid is 29739 and current tid(lwp_id) is 29739

主线程和新线程的PID是相同的,这是因为POSIX的规定:同一个程序中的所有线程应该有相同的PID.
但是二者的轻量级进程ID(lwp)并不相同. 因为linux就是通过lwp来实现线程的。