ÉèÖÃLinuxϵͳÒÔÖ§³Ö¶àÏ̱߳à³Ì
ÉèÖÃlinuxϵͳÒÔÖ§³Ö¶àÏ̱߳à³Ì
ÔÚÄ¿½ñÅÌËã»úÓ¦ÓóÌÐòµÄ¿ª·¢ÖУ¬¶àÏ̱߳à³ÌÒѾ±äµÃ·Ç¾³£¼û¡£¶àÏ̱߳à³Ì¿ÉÒÔÔÊÐí³ÌÐòͬʱִÐжà¸öʹÃü£¬´Ó¶øÌá¸ßϵͳÐÔÄܺÍÏìÓ¦ÄÜÁ¦¡£±¾ÎĽ«ÏÈÈÝÔõÑùÉèÖÃlinuxϵͳÒÔÖ§³Ö¶àÏ̱߳à³Ì£¬²¢¸ø³öһЩ´úÂëʾÀý¡£
×°ÖÃÐëÒªµÄÈí¼þ°ü
Ê×ÏÈ£¬ÎÒÃÇÐèҪװÖÃһЩÐëÒªµÄÈí¼þ°ü£¬ÒÔ±ãÔÚLinuxϵͳÉϾÙÐжàÏ̱߳à³Ì¡£¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´×°ÖÃÕâЩÈí¼þ°ü£º
sudo apt-get update sudo apt-get install build-essential sudo apt-get install libpthread-stubs0-dev
µÇ¼ºó¸´ÖÆ
build-essentialÈí¼þ°üÌṩÁ˱àÒëºÍÁ´½ÓËùÐèµÄ¹¤¾ßºÍ¿â¡£libpthread-stubs0-devÈí¼þ°üÌṩÁËÓëPOSIXÏ߳̿âÏà¹ØµÄÍ·ÎļþºÍ¾²Ì¬¿â¡£
±àд¶àÏ̳߳ÌÐò
½ÓÏÂÀ´£¬ÎÒÃǽ«±àдһ¸ö¼òÆӵĶàÏ̳߳ÌÐòÀ´ÑÝʾÔõÑùÔÚLinuxϵͳÉϾÙÐжàÏ̱߳à³Ì¡£ÎÒÃǽ«Ê¹ÓÃCÓïÑÔºÍPOSIXÏ߳̿âÀ´±àдÕâ¸ö³ÌÐò¡£Ç뽫ÒÔÏ´úÂëÉúÑÄΪmain.cÎļþ¡£
#include <stdio.h> #include <pthread.h> #define NUM_THREADS 5 void *threadFunc(void *arg) { int threadNum = *(int*)arg; printf("This is thread %d ", threadNum); pthread_exit(NULL); } int main() { pthread_t tid[NUM_THREADS]; int i; for (i = 0; i < NUM_THREADS; i++) { int *threadNum = malloc(sizeof(int)); *threadNum = i; pthread_create(&tid[i], NULL, threadFunc, threadNum); } for (i = 0; i < NUM_THREADS; i++) { pthread_join(tid[i], NULL); } return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸ö³ÌÐòÖУ¬ÎÒÃǽç˵ÁËÒ»¸öthreadFuncº¯Êý£¬Ëü×÷Ϊÿ¸öÏ̵߳ÄÈë¿Úµã¡£ÔÚÕâ¸öº¯ÊýÖУ¬ÎÒÃǼòÆӵشòÓ¡³öÏ̵߳ıàºÅ¡£
ÔÚÖ÷º¯ÊýÖУ¬ÎÒÃÇʹÓÃpthread_createº¯Êý½¨ÉèÁËNUM_THREADS¸öỊ̈߳¬²¢½«ËüÃǵıàºÅת´ï¸øthreadFuncº¯Êý¡£È»ºó£¬ÎÒÃÇʹÓÃpthread_joinº¯ÊýÆÚ´ýËùÓÐÏ̵߳Ŀ¢Ê¡£
±àÒëºÍÔËÐгÌÐò
ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´±àÒëÕâ¸ö³ÌÐò£º
gcc -o program_name main.c -lpthread
µÇ¼ºó¸´ÖÆ
ÕâÀ-lpthreadÑ¡ÏîÓÃÓÚÁ´½ÓPOSIXÏ߳̿⡣
ÔÚ±àÒëÀֳɺó£¬ÎÒÃÇ¿ÉÒÔÔËÐгÌÐò£º
./program_name
µÇ¼ºó¸´ÖÆ
µ±ÔËÐгÌÐòʱ£¬ÎÒÃǽ«¿´µ½Êä³öÏÔʾÁËÿ¸öÏ̵߳ıàºÅ¡£
×ܽá
±¾ÎÄÏÈÈÝÁËÔõÑùÉèÖÃlinuxϵͳÒÔÖ§³Ö¶àÏ̱߳à³Ì£¬²¢¸ø³öÁËÒ»¸ö¼òÆӵĶàÏ̱߳à³ÌʾÀý¡£Í¨¹ý³ä·ÖʹÓöàÏ̱߳à³Ì£¬ÎÒÃÇ¿ÉÒÔÌá¸ßϵͳµÄÐÔÄܺÍÏìÓ¦ÄÜÁ¦¡£Ï£Íû±¾ÎĶÔÄãÔÚLinuxϵͳÉϾÙÐжàÏ̱߳à³ÌÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇÉèÖÃLinuxϵͳÒÔÖ§³Ö¶àÏ̱߳à³ÌµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡