分类: C/C++
2005-10-20 13:12:08
1.创建线程
(linux)
//thread.c
#include
#include
#include
void * new_thread(void * args)
{
int i=0;
int *p=(int *) args;
while(i++<10){
sleep(1);
printf("I am wake up now and will sleep agin
");
}
}
int main()
{
pthread_t thread;
int i=0;
pthread_create(&thread,NULL,new_thread,&i);
pthread_join(thread,NULL);
}
编译命令如下 gcc thread.c -lpthread
(window)
#include
#include
#include
DWORD WINAPI new_thread( void * parm)
{
cout<<"hello<<\n";
return 0;
}
void main()
{
DWORD dwThread;
CreateThread(NULL,0,new_thread,NULL,0,&dwThread);
Sleep(10);//不能少,少了就看不到输出的效果了。
}
2.线成同步:
#include
#include
#include
int buff[16];
int num;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * producer(void * args){
//int i=produce();
// int i=pthread_mutex_trylock(&mutex);
pthread_mutex_lock(&mutex);
sleep(1);
printf("producer finished work
");
pthread_mutex_unlock(&mutex);
}
void * user(void * args){
int i=pthread_mutex_trylock(&mutex);
// if(i==EBUSY)
// printf("the mutex is locked
");
printf("the mutex should be locked,does it show quicker
");
pthread_mutex_lock(&mutex);
printf("int user function
");
pthread_mutex_unlock(&mutex);
}
int main()
{
int i=0;
pthread_t pro,usr;
pthread_create(&pro,NULL,producer,&i);
pthread_create(&usr,NULL,user,&i);
pthread_join(pro,NULL);
pthread_join(usr,NULL);
}
3. 线程signal
#include
#include
#include
pthread_mutex_t mutex;
pthread_cond_t cond;
int num=0;
void * child1(void *arg)
{
pthread_cleanup_push(pthread_mutex_unlock,&mutex); /* comment 1 */
while(1){
printf("thread 1 get running \n");
printf("thread 1 pthread_mutex_lock returns
%d\n",pthread_mutex_lock(&mutex));
pthread_cond_wait(&cond,&mutex);
printf("thread 1 condition applied\n");
pthread_mutex_unlock(&mutex);
sleep(5);
}
}
pthread_cleanup_pop(0); /* comment 2 */
}
void *child2(void *arg)
{
while(1){
printf("thread 2 get running.\n");
printf("thread 2 pthread_mutex_lock returns %d\n",pthread_mutex_lock(&mutex));
printf("thread 2 condition applied\n");
while(num<=0){
pthread_cond_wait(&cond,&mutex);
}
num--;
pthread_mutex_unlock(&mutex);
printf("consume one \n");
// sleep(1);
}
}
int main(void)
{
int tid1,tid2;
printf("hello, condition variable test\n");
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
// pthread_create(&tid1,NULL,child1,NULL);
pthread_create(&tid2,NULL,child2,NULL);
char a;
do{
//
sleep(2);
/* comment 4 */
//
pthread_cancel(tid1); /* comment 5
*/
//
sleep(2);
/* comment 6 */
scanf("%c",&a);
pthread_mutex_lock(&mutex);
num++;
printf("product 1\n");
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}while(1);
sleep(100);
pthread_exit(0);
}