Finally, the linux multi-thread compilation and multi-thread compilation errors are implemented.
Source: Internet
Author: User
Finally, the linux multi-thread compilation and multi-thread compilation errors-Linux general technology-Linux programming and kernel information are implemented. The following is a detailed description. I wrote a thrdcreat. c source file as follows:
/*
* Thrdcreat. c -- initialize strate creating a thread
*/
Int main (int argc, char * argv [])
{
Pthread_t thrd1, thrd2;
Int ret;
/* Create the first thread */
Ret = pthread_create (& thrd1, NULL, (void *) task1, (void *) & g1 );
If (ret)
{
Perror ("pthread_create: task1 ");
Exit (EXIT_FAILURE );
}
/* Create the second thread */
Ret = pthread_create (& thrd2, NULL, (void *) task2, (void *) & g2 );
If (ret)
{
Perror ("pthread_create: task2 ");
Exit (EXIT_FAILURE );
}
Pthread_join (thrd2, NULL); // wait for execution in the first thread and get started. After the second thread is executed, the first thread continues to execute.
Pthread_join (thrd1, NULL );
Cleanup (g1, g2 );
Exit (EXIT_SUCCESS );
}
Void cleanup (int counter1, int counter2)
{
Printf ("total iterations: % d \ n", counter1 + counter2 );
}
I thought it was a success, but it always showed up during compilation:
[Hyj @ localhost cfile] $ gcc-o thrdcreat. c
/Tmp/ccorDWTW. o: In function 'main ':
Thrdcreat. c :(. text + 0x31): undefined reference to 'pthread _ create'
Thrdcreat. c :(. text + 0x76): undefined reference to 'pthread _ create'
Thrdcreat. c :(. text + 0xaa): undefined reference to 'pthread _ join'
Thrdcreat. c :(. text + 0xbd): undefined reference to 'pthread _ join'
Collect2: ld returns 1
Pthread_create and pthread_join are not defined? Impossible. I have a header file # include Yes.
Later, I checked a lot of information and found that the thread library should be specified during compilation. Otherwise, such errors will occur.
To solve this problem, add-lpthread after gcc during compilation.
[Hyj @ localhost cfile] $ gcc-o thrdcreat. c-lpthread
[Hyj @ localhost cfile] $./thrdcreat
Task1 count: 0
Task2 count: 0
Task2 count: 1
Task2 count: 2
Task2 count: 3
Task2 count: 4
Task1 count: 1
Task1 count: 2
Task1 count: 3
Task1 count: 4
Total iterations: 10
: 0wpoi2
Success.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.