pthread 互斥实例

/* file name: main.c file desc: pthread mutex testing...under gcc 3.4.5 (c) Tody 2010, T-ware Inc. This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <windows.h> pthread_mutex_t mutex; const char *Msg="AbCdEfGhIjKlMnOpQrStUvWxYz"; char *p = NULL; void threadproc() { char buf[14] = {0}; int i = 0; printf("thread: %d is Running.../n", pthread_self()); pthread_mutex_lock(&mutex); // start to lock { for(i=0; i<13; i++) { buf[i] = *p++; } } pthread_mutex_unlock(&mutex); // here end lock printf("%s/n", buf); Sleep(500); pthread_exit(NULL); } int main(int argc, char *argv[]) { pthread_t t, t1; int ret = 0; p = (char *)Msg; pthread_mutex_init(&mutex, NULL); // init mutex var. ret = pthread_create(&t, NULL, (void *)threadproc, NULL); if (ret != 0) { exit(1); } ret = pthread_create(&t1, NULL, (void *)threadproc, NULL); if (ret != 0) { exit(1); } pthread_join(t, NULL); pthread_join(t1, NULL); pthread_mutex_destroy(&mutex); // destory mutex var. //system("PAUSE"); return 0; }

你可能感兴趣的:(JOIN,thread,File,gcc,null,library)