[{"content":"Recently, I stumbled upon a video on Bilibili where a 38-year-old software developer shared his frustrations about being unable to find a job. Video Link。Watching it brought back memories, as I too experienced over four months of unemployment in 2023. The self-doubt during that period was deeply impactful. However, this article isn\u0026rsquo;t about reminiscing over tough times but rather to explore whether 35 is truly the end of the road for software developers. Is it really inevitable that programmers must \u0026ldquo;retire\u0026rdquo; at 35, unable to find work or forced to change careers?\nAge 35 Is Not the End Currently, various factors, including the economic downturn, have led to widespread layoffs across industries. Companies are tightening their belts, and there’s little we can do about external factors. The job market is saturated, and companies are raising the bar for hiring, leading to increasingly difficult interviews. Some call this \u0026ldquo;involution,\u0026rdquo; but I see it as a natural adjustment in the talent market. Companies elevate their hiring standards to attract top talent, and the market responds accordingly.\nHowever, not every software developer has maintained a habit of learning and staying technically sharp. When China’s internet industry began to boom in 2010, with \u0026ldquo;Internet Plus\u0026rdquo; connecting everything, a wave of new companies emerged. Developers rode this wave, earning high salaries. Some became complacent, failing to keep up with the times, and were consequently left behind when the economy turned south. In the video, the creator admits to spending much of his free time gaming instead of delving into fundamental knowledge, thinking that if it wasn\u0026rsquo;t directly applicable to his work, it wasn\u0026rsquo;t worth learning. This complacency led to a dislike of technology later on, suggesting that he never truly loved software development but merely stumbled into the then-lucrative internet industry. With the wave gone, job interviews became difficult, and companies hesitated to hire a 38-year-old developer who lacked essential skills. His weak English skills further limited his options for remote or overseas work, trapping him in a frustrating situation.\nThat said, even if we are well-versed in the latest technologies, we may still face job challenges. For example, before 2015, most web developers used jQuery, but after 2015, the industry shifted to frameworks like Angular, Vue, and React. Later, tools like Tailwind CSS simplified the complexities of CSS, making it easier for a new generation of front-end developers. If you\u0026rsquo;re still relying solely on jQuery in 2024, what reason does the market have to keep you?\nDespite the challenges mentioned above, I firmly believe that \u0026ldquo;35 is not the end for software developers.\u0026rdquo;\nThe Rules of the Software Industry: Why Give Simple Tasks to Younger Workers? After 3-5 years of software development experience, you\u0026rsquo;ll realize that most daily tasks—developing features, debugging bugs—aren\u0026rsquo;t particularly complex. The real challenges lie in areas beyond a developer\u0026rsquo;s typical knowledge and in solving industry-wide, unsolved problems. If someone enters the software industry at 23 and spends 12 years doing routine work without seeking breakthroughs or understanding the underlying logic of the code, it’s easy to stagnate. On the surface, companies might give small raises each year to retain \u0026ldquo;useful\u0026rdquo; employees, but this can mask the fact that some developers are just treading water, losing their passion for technology, and becoming unaware of their stagnation.\nSo why shouldn’t companies assign simple tasks to younger workers? If, by 35, you haven’t accumulated enough knowledge to do more than basic tasks, or if you can\u0026rsquo;t guide younger developers and only engage in surface-level coding, then what value do you bring to the company?\nI believe the real issue is that many people don’t realize how fast the software industry evolves. A computer costing less than $500 can provide access to the latest programming technologies, and an internet connection allows anyone to read the most sophisticated operating system and framework source codes. This level of access is unimaginable in other industries. For software developers, this is a great equalizer, offering everyone the opportunity to learn. Yet, some videos discourage people from entering the software industry, claiming it’s too fast-paced and requires constant learning. But is it really more exhausting than being a doctor, a teacher, or a factory worker? Sitting in an air-conditioned office, drinking tea, listening to music, and reading source codes and documentation—all without needing to enter a lab to experiment—how can this be considered overly challenging? On the contrary, being able to observe the world’s best developers debate and discuss technology is a fascinating experience.\nIf, by 35, you still don’t understand the rules of the software industry or can’t keep up with its pace of change, then being phased out is a natural outcome. To persist in any industry, you must have your own values, dreams, or passion. Without these, if you entered the software industry solely for the money, you’ll likely leave when the money dries up.\nResponsibility: A Necessity for Adults Responsibility is often seen as a burden, something that’s not always rewarded. But in your career, there will be moments when you need to step up and take responsibility. Whether it\u0026rsquo;s ensuring code quality during a review or being accountable for a project’s outcome, responsibility is an essential skill for career advancement. Knowing how to choose the right responsibilities, how to handle them well, and how to manage situations when you’re unfairly blamed are challenges that go beyond software code—they’re about communication and interest negotiation. When faced with these issues, which aren’t covered in technical books but are common in the workplace, you need to adjust your mindset, understand what you want, and maintain a positive attitude. This requires time and self-discipline.\nI’ve seen many people who, after being promoted, weren\u0026rsquo;t ready to take on responsibility. When they realized the task was beyond their capabilities, they experienced a \u0026ldquo;fight-or-flight\u0026rdquo; response—an ancient reaction to danger. Since \u0026ldquo;fighting\u0026rdquo; isn’t an option in an office, they often respond with anger or simply avoid the problem by taking time off. They want the benefits of a promotion without accepting the increased responsibility, which is unreasonable. But many do exactly this, letting their anxiety affect the entire team’s morale.\nTaking responsibility doesn’t always lead to immediate benefits, but if you understand why you’re taking on a responsibility and the potential rewards, it can be worthwhile. If the responsibility doesn’t directly lead to benefits, you can use it as leverage in negotiations with others. If there are no benefits at all, it’s best to step back and let others see the issue’s flaws.\nIn China’s education system, especially during compulsory and high school education, there’s little emphasis on team responsibility. Everyone focuses on their own grades and future, and when teamwork is involved, some may shirk responsibility, with teachers only concerned about the outcome. This often leaves one particularly capable or bullied student to do most of the work. As a result, many don’t understand what responsibility means or how to cultivate it. I’m not saying everyone should be selfless, but the lack of teamwork awareness can lead to some taking advantage of strong team members. This is not a healthy mindset.\nLearning to take responsibility involves:\nClearly understanding your responsibilities and fulfilling them within your scope. Knowing the benefits of taking responsibility and whether they justify your efforts. If not, communicate with your superiors to negotiate your interests. Going further, if the team needs you, do what you can to help others. Think from the team’s perspective, understand higher-level responsibilities, and use your abilities to make a difference. The More You Experience, the More You Grow Throughout life, I’ve heard many pieces of advice. Some make sense only after experiencing them yourself; others may never be shared with you. Some advice is given with ulterior motives. But no matter the source, you’ll never fully grasp these lessons until you’ve lived through them. As the saying goes, \u0026ldquo;You can’t understand the world by merely reading about it; true understanding comes from direct experience.\u0026rdquo;\nOur world is constantly changing, and the problems we face are diverse and often lack clear-cut solutions. It can be disheartening when work-related issues don’t have perfect answers. But if you can separate your self-worth from your work and recognize that these problems mean nothing outside of your job, you’ll be able to think more positively about the challenges you face and the deeper reasons behind them, rather than blaming yourself for every issue.\nEven when you think you’ve learned a lot and overcome many challenges, remember not to be condescending. Everyone has their own path, their own obstacles—what some might call \u0026ldquo;the trials of life.\u0026rdquo; Though it may sound mystical, the reality is that each person’s unique circumstances, personality, and background create their own set of challenges. Simply telling them the answers won’t help them truly learn those lessons. Whether dealing with superiors, peers, friends, or younger individuals, always respect their opportunity to experience and grow.\nNever Limit Yourself We’ve discussed why it’s hard to find a job at 35, but every industry has its more challenging aspects that require pioneers to tackle. At 35, you’re at a prime age: you’ve accumulated theoretical knowledge from school, gained practical experience at work, and faced some tough industry problems. While you may no longer have the boundless energy of a fresh graduate, you’re still more than capable of tackling difficult issues. I believe that one reason 35 has become a perceived barrier is that some people, feeling the pressure of age, start to limit themselves, blaming their job difficulties on their age.\nTake, for example, the Wine software—a framework that allows Windows applications to run on Mac and Linux systems. Wine regularly hires remote developers from around the world to work on their software. They’re currently looking for a General Wine Developer.（https://www.codeweavers.com/about/jobs），Here’s a glimpse of the job requirements:\n[Requirements] Strong C language skills. Compilers, linkers, macros and function pointers don\u0026#39;t scare you. Excellent debugging skills. You will be debugging applications whose source you do not have. Familiarity with developing on and administering a Linux system (bash, unix utilities, package management, etc) Ability to understand and debug build systems (Makefiles, autotools, etc) Understanding of good development practices (source control, atomic commits, code readability, test-driven development) Self-motivated to find work and learn new skills No exposure to Microsoft code or reverse-engineering of Microsoft software [Bonus skills we want] not required, but it helps Win32 programming experience Systems-level programming experience Previous contributions to open source software How many programmers can truly meet these requirements? And considering that Wine is open-source software, anyone can access the source code without even logging in. But how many are willing to study the code and contribute to its development?\nIf you find it difficult to secure a job in China, have you considered learning English and seeking opportunities abroad? Those who are genuinely passionate about the software industry, willing to invest time and effort to deepen their expertise, or analyze potential demands and solve them through their software skills, should not find themselves unable to make a living. Over the past decade, software industry training programs have produced a wave of programmers who entered the field for financial gain. During economic downturns, it\u0026rsquo;s natural that some of these individuals may be weeded out. However, when we look at the big picture, the software and computer industries are undergoing transformations with AI, continuously impacting every aspect of our lives. How can we so quickly conclude that the software industry has no future?\nEven if one cannot contribute to the industry with boundless enthusiasm, why not be a trailblazer who guides newcomers and helps them avoid pitfalls? Pioneers like \u0026ldquo;Left Ear Mouse,\u0026rdquo; Ruan Yifeng, Liao Xuefeng, and Yun Feng from the gaming industry have been sharing their insights and understanding for decades. They are leading the charge in writing better software and encouraging deeper thinking within the industry.\n","permalink":"https://windypath.com/en/posts/35_not_the_end_of_software_developer/","summary":"\u003cp\u003eRecently, I stumbled upon a video on Bilibili where a 38-year-old software developer shared his frustrations about being unable to find a job. \u003ca href=\"https://www.bilibili.com/video/BV1CT421m7Mx\"\u003eVideo Link\u003c/a\u003e。Watching it brought back memories, as I too experienced over four months of unemployment in 2023. The self-doubt during that period was deeply impactful. However, this article isn\u0026rsquo;t about reminiscing over tough times but rather to explore whether 35 is truly the end of the road for software developers. Is it really inevitable that programmers must \u0026ldquo;retire\u0026rdquo; at 35, unable to find work or forced to change careers?\u003c/p\u003e","title":"Age 35 Is Not the End for Software Developers"},{"content":"Recently, I participated in an independent game project powered by passion, where a group of online friends came together to remake a single-player game set in the Three Kingdoms period. \u0026ldquo;Powered by passion\u0026rdquo; here means working without pay, driven solely by the desire to pursue a dream. From February 4, 2024, when I first learned about the group, to February 7, when I joined, and up until April 4, when I left, I spent a total of two months on this project.\nI don\u0026rsquo;t want to dwell too much on the issues I encountered in this development team, as they were quite specific to the group and not necessarily applicable to other situations. Instead, I want to share some insights and advice for individual developers who might be considering joining a passion-driven project.\nTimeline 2/4: Learned about the project. 2/6: Passed the interview and joined the team. 2/7 - 2/17: Took a break for the Chinese New Year, didn\u0026rsquo;t study project-related materials, and felt slightly pressured (lightly \u0026ldquo;PUA\u0026rsquo;ed\u0026rdquo;). 2/18 - 2/24: Began learning about the project. 2/24: Fixed the first bug. 2/25 - 3/30: Fixed a total of six bugs, ranging from minor to significant. 3/30 - 4/4: Realized much of my work involved cleaning up others\u0026rsquo; mistakes, found it meaningless, and felt that I had wasted too much personal time on the project. 4/4: Decided to leave the team.\nTeam Issues The main problems with this team were the lack of comprehensive documentation and the heavy reliance on video tutorials, which were too low in information density and difficult to follow. Additionally, many features in the previous project\u0026rsquo;s codebase were only half-finished, with the unfinished parts left to be treated as bugs. This made it very challenging for the bug fixers, as it was unclear where the feature boundaries lay, leading to a lot of uncertainty during the fixing process. The lack of proper documentation made modifications even harder. Lastly, with no financial incentives in passion-driven projects, it often felt like working for free, with no tangible rewards such as GitHub stars or other forms of recognition, leading to burnout over time.\nThe Passion-Driven Mindset From my experience in this project, I\u0026rsquo;ve gathered a few key takeaways:\nMore Free Time Than You Think: You often have more free time than you realize. Sometimes, just one or two hours of high-efficiency work can achieve a lot. If you have a clear expectation of what you want to accomplish, it won\u0026rsquo;t feel burdensome, and completing small milestones can be incredibly satisfying. Don\u0026rsquo;t Rush Big Projects: For large projects, don’t rush to complete all the features at once. Take time to organize modules. When working on features, clearly distinguish between \u0026ldquo;unfinished features\u0026rdquo; and \u0026ldquo;bugs.\u0026rdquo; For unfinished features, analyze them, estimate the time needed, and advance gradually. For bugs, analyze the cause, distinguish between correct and incorrect results, and discuss solutions only after thorough analysis. This is a long process, so don\u0026rsquo;t slack off just because there’s no immediate reward. Set Realistic Expectations: If the project doesn’t offer direct compensation, you need to control your expectations and find a personal reason to keep going. And if there’s no direct compensation, don’t feel guilty about quitting. Choosing the Right Project Here are some lessons I’ve learned about selecting the right project team:\nIf There’s No Direct Compensation, Get Something Else: If a project doesn’t provide direct compensation (like this team or contributing to a public GitHub repository), make sure to get something else in return (like GitHub stars, industry reputation, resources, or connections). Alternatively, ensure the project itself is interesting, valuable, or promising. Don’t accept nothing, as that goes against the basic principles of value. If nothing is provided, the project is likely of little value and not worth your time. Don’t Rely on Empty Promises: Perseverance requires substance. Sustainable effort comes from working on something valuable that you slowly build over time. Maintain a Main Occupation: Having a stable means of livelihood is essential to support your dreams. Alternatively, if a project offers valuable resources and connections, it’s worth your time. Be Ready to Pivot: Don’t be afraid to change direction. Don’t get stuck on one path, and don’t fear making mistakes. No compensation means no obligation. While responsibility is generally encouraged, it should never come at the cost of your own well-being. Project Summary I can’t say I was entirely blameless in this group. In fact, I started from scratch with Lua and found that learning the entire codebase took longer than expected. Weakly typed languages and game client development differ somewhat from game server development. I spent more time than I anticipated getting up to speed with the basic project framework. This experience taught me that understanding open-source projects and helping with them is a rare skill. Reading others\u0026rsquo; code has its own set of challenges, not just in terms of language, framework, and design but also in navigating without real-time answers. When no one is there to provide guidance, how do you learn from just the source code and runtime environment (if the project even doesn\u0026rsquo;t have one)? This challenge includes whether we have enough free time to dedicate to these projects.\nSo, asking \u0026ldquo;Why am I doing XXX?\u0026rdquo; is a very valuable question. If it’s for a better-looking resume, then it might be more effective to just study for interviews, practice coding problems, and learn about frameworks and common design patterns. If you think it’s \u0026ldquo;interesting,\u0026rdquo; then consider whether the project’s level of fun is enough to replace your usual leisure activities (like travel, gaming, or socializing). If not, then maybe it’s not worth pursuing. If it’s to learn a trending technology, is that technology really worth your time? Perhaps it’s better to figure these things out before diving in.\nAdditionally, studying someone else’s project code can be incredibly tedious. Programming offers a lot of creative freedom, so everyone has their own design solutions. Despite coding standards, people often get stuck in their own way of thinking. It’s essential to have an open mind when trying to understand code. More importantly, when facing difficulties, it’s crucial to assess the project’s value and make the most of every moment. After all, your free time should belong to you.\nFinally, remote communication is fraught with noise. A single word or sentence can easily be misinterpreted, which is why technical documentation is so important. Good documentation should be unambiguous and able to convey a lot of information, sometimes even more important than the code itself. Especially when communication is not face-to-face, how to maintain alignment and move forward together is a complex issue. In my two months on this project, I’ve realized that both parties must have high technical skills, excellent communication, and sufficient patience and responsibility for things to progress smoothly. This might be why remote work tends to favor hiring senior developers.\nThoughts on Open Source This section is not directly related to the passion-driven project but is also a reflection from the past two months.\nSince May 2023, I’ve started playing Counter-Strike again, a game whose abbreviation, CS, coincidentally matches Computer Science. Sometimes I find it quite fitting, as I chose CS as my major in university, worked in the CS field, and now am almost \u0026ldquo;addicted\u0026rdquo; to the game CS.\nOne recent insight comes from a discussion by a CS streamer, Shyeark, about what it takes to become a professional CS player. In this video, Shyeark mentions that many talented CS players reached the top ranks with around 700 hours of playtime, after which they were invited to join professional teams. On the other hand, most casual players with dreams of \u0026ldquo;going pro\u0026rdquo; lack the talent necessary to become professional players. Shyeark concludes that most professional players became pros simply because they genuinely enjoyed playing CS , discovered they could play at a higher level, and wanted to compete with better players.\nI see a similar pattern among open-source project maintainers. Take, for instance, Vue’s creator, Evan You, who developed Vue in his spare time while working at Google. Due to its simple and user-friendly design, it quickly gained attention from developers. But initially, the core team only had four members at the 15:06 mark of this video. This shows that most people can’t truly contribute to GitHub projects because they lack the necessary passion and talent (yes, I’m talking about myself). Uploading your code as open-source and maintaining it for the community without compensation is similar to how current CS pros practice their skills, learn new strategies, and compete in tournaments without a robust support system like that of League of Legends. It requires both passion and talent. Only with enough passion can they keep striving for something intangible, and only with talent can they reach the pinnacle of their skills and gain global recognition and support.\nFinding a valuable project, sticking with it, and waiting for a result, whether good or bad, is a process that will always yield some reward.\nOpen-source developers who contribute for recognition alone, like those who play CS just to become professional players, won’t last long. The only sustainable motivation for such unpaid endeavors is passion and habit. Apart from the external rewards of money, fame, or honor, ask yourself: does what you do in your spare time truly bring you joy? If not, then perhaps it’s not worth the effort.\nI remember the autobiography of Linux creator Linus Torvalds titled Just For Fun. It also brings to mind an interview with Meiko, a support player for EDG who won multiple championships, where he mentioned something like, \u0026ldquo;League of Legends is genuinely fun.\u0026rdquo; Linus didn\u0026rsquo;t start writing Linux with the idea of \u0026ldquo;creating a better operating system than UNIX,\u0026rdquo; and Meiko didn\u0026rsquo;t start playing LOL with the belief that he would become the world\u0026rsquo;s best support player. But eventually, they both achieved their goals, driven by passion and persistence.\nHonestly, I’m not yet at a point where I can quickly dive into an unfamiliar field, nor have I found an open-source project that I’m particularly passionate about. So, for now, I\u0026rsquo;ll focus on my job, read more books, and explore open-source projects to broaden my horizons, all while waiting for \u0026ldquo;that project\u0026rdquo; that truly resonates with me.\n","permalink":"https://windypath.com/en/posts/two_month_voluntary_project_conclusion/","summary":"\u003cp\u003eRecently, I participated in an independent game project powered by passion, where a group of online friends came together to remake a single-player game set in the Three Kingdoms period. \u0026ldquo;Powered by passion\u0026rdquo; here means working without pay, driven solely by the desire to pursue a dream. From February 4, 2024, when I first learned about the group, to February 7, when I joined, and up until April 4, when I left, I spent a total of two months on this project.\u003c/p\u003e\n\u003cp\u003eI don\u0026rsquo;t want to dwell too much on the issues I encountered in this development team, as they were quite specific to the group and not necessarily applicable to other situations. Instead, I want to share some insights and advice for individual developers who might be considering joining a passion-driven project.\u003c/p\u003e","title":"Reflections on Two Months of Working on a Passion-Driven Project"},{"content":" The following content is excerpted from the internet.：《魏略》蜀军大将魏延认为，长安守将夏侯楙年少，娇生惯养、怯而无谋。今日假若我魏延领精兵五千，背负粮草五千，直由山道深入，寻秦岭而向东，到达子午再往北行。不过十日就能抵达长安。夏侯楙见我军突然出现，必然乘船而逃。如此一来，长安城内只剩下御史、京兆太守而已。长安北门有散民之谷，足以供应我军粮食。而由东方相会合，需要二十日，届时丞相您在由斜谷赶来，必定可以在此与我会师，这么一来，可以一举平定咸阳以西。\nMusings on the Ziwu Valley Strategy When I first heard about Wei Yan\u0026rsquo;s \u0026ldquo;Ziwu Valley Strategy\u0026rdquo; as a teenager, I couldn\u0026rsquo;t help but lament that Zhuge Liang did not adopt it. However, after years of experience, especially as I\u0026rsquo;ve listened to game designers and developers argue about project requirements in the office, I gradually came to understand why Zhuge Liang rejected this plan 1,800 years ago.\nWarfare in ancient times was a brutal affair. Ordinary people, conscripted by the government, had to abandon their farm work, receive minimal training, and were then thrust into battle as soldiers. Every soldier conscripted meant one less farmer, leading to potential food shortages if too many were taken from the fields. Without enough farmers to sustain agriculture, food scarcity would ensue, forcing armies to plunder resources elsewhere, leading to campaigns of \u0026ldquo;eastward conquests and westward expeditions.\u0026rdquo; The saying, \u0026ldquo;For every general\u0026rsquo;s success, a thousand bones lie dry,\u0026rdquo; aptly describes this cycle. After capturing a city, commanders often allowed their soldiers to loot, leading to what history coldly records as a \u0026ldquo;massacre.\u0026rdquo;\nHowever, Liu Bei and Zhuge Liang\u0026rsquo;s faction in the Three Kingdoms era had no records of massacres. Objectively speaking, Liu Bei’s true rise began after he secured Zhuge Liang from Jingzhou. The plains of Jingzhou and Yizhou were vast, free from constant warfare, and blessed with abundant food supplies. Liu Bei\u0026rsquo;s forces did not need to massacre to obtain enough grain. Subjectively, Liu Bei might have genuinely adhered to his ideals or felt a responsibility as a member of the Han royal family to genuinely \u0026ldquo;cherish the people like his own children.\u0026rdquo; During the late Shu-Han period, Zhuge Liang, in his six campaigns against the state of Wei, chose not to wage endless wars but allowed his soldiers to farm and stockpile grain. Despite the treacherous Shu roads being as difficult to traverse as ascending the heavens, the broad Chengdu plains ensured the local people lived comfortably. Chengdu was known for producing the beautiful Shu brocade, which was exported far and wide. Life in Chengdu was far better than for the northern populace in the early 200s. Though Zhuge Liang\u0026rsquo;s kindness is not explicitly written in historical records, it resonates across 1,800 years to touch the hearts of all who love the history of the Three Kingdoms.\nWould such a compassionate commander really be willing to risk the lives of 5,000 soldiers? Those soldiers, once they removed their armor, were merely mountain farmers. Perhaps behind those 5,000 soldiers were 5,000 pairs of parents, 5,000 wives, and countless children. Would such a risky decision be irresponsible toward those left behind?\nFrom Wei Yan\u0026rsquo;s perspective, however, after the Five Tiger Generals and before Jiang Wei (whom he had yet to meet), there was no one more powerful or prestigious than him. For a soldier, wartime is the golden opportunity to make a name for oneself. If he could capture Chang\u0026rsquo;an in one bold stroke, he would become the top military officer of Shu-Han. Driven by such ambition, proposing such a risky strategy is understandable.\nAs I grew older and came to grasp the brutal realities of war and the unpredictability of human nature, I realized that Wei Yan\u0026rsquo;s so-called \u0026ldquo;brilliant plan\u0026rdquo; was nothing more than a wild gamble, risking 5,000 lives for a slim chance at historical fame. It is no wonder Zhuge Liang dismissed it. Even if Chang\u0026rsquo;an were captured, what then? The state of Wei controlled almost all of the northern territories and had many seasoned generals who had fought alongside Cao Cao. Could Wei Yan really hold onto the city? The answer is obvious.\nSo, why do people still discuss the \u0026ldquo;what ifs\u0026rdquo; in the 21st century? I believe it’s partly because many people genuinely regret the repeated failures of Zhuge Liang and Jiang Wei\u0026rsquo;s campaigns, and partly because Wei Yan\u0026rsquo;s strategy did have a sliver of potential—perhaps it could have given Shu-Han an edge. But they never fully consider what the next step would have been if they succeeded, or the massive losses if they failed.\nSoftware Engineering as the Art of War in the Software Industry Almost all stable software in operation today is supported by a maintenance team. This team typically does two things: develop new features and fix bugs. How to iterate versions steadily, how to maintain the usability of developed features, how to ensure that new features do not affect old ones, and how to minimize users\u0026rsquo; learning costs for new features—all fall within the realm of software engineering. If we liken software development to a battle, then designing software is akin to formulating tactics, developing software is like recruiting troops, launching and releasing software is like marching to war, and facing users is the front line of the battlefield. If there is an emergency on the front line, commanders must promptly allocate resources and resolve issues.\nTo smoothly navigate the development, release, and maintenance processes, software engineering offers various development models, such as the waterfall model, rapid prototyping, incremental model, and agile model. When first learning these models, one might find them convoluted and difficult to grasp. But simply put, they describe how to allocate manpower to complete a series of processes: requirement analysis, software design, software development, software release, and software maintenance. In the past, when using the waterfall model, clients couldn’t see the expected results during the software development process and only encountered the final product after its completion. If the client was dissatisfied, the whole process had to be redone. Later, people proposed first designing a prototype for the client to review, drafting a glossary to ensure that the discussions were aligned with the goals (this is also the concept behind Domain-Driven Design, DDD). Another approach is to break down the requirements, complete one, and release it—this is the incremental model. Or, increase the number of deliveries, use the agile model, and take a specific time length as the output cycle, providing weekly feedback (not necessarily completing the entire function, but at least part of it). These optimized development models aim to allow the client to observe the software development process as early as possible.\nHowever, in the current software industry, both domestically and internationally, most teams do not strictly follow these development models. Many complex factors are behind this. Clients, as the demanding party, might not clearly define what they want; developers, as the service providers, might exaggerate their capabilities to win contracts; and programmers might misunderstand the requirements slightly differently than their leaders. Not to mention technical selection, performance indicators, and other aspects that require time-consuming analysis. Fully adhering to advanced development models requires that the client, developer, and entire development team be above a certain competency level (though what constitutes a \u0026ldquo;competent\u0026rdquo; level is hard to define) and engage in effective, thorough communication.\nNow, let\u0026rsquo;s talk about requirement changes. Requirement changes are almost unavoidable in the software industry. In fact, there’s hardly any demand in the world that remains unchanged. However, the cost of requirement changes in the software industry is often difficult to estimate accurately. Software is intangible data that we merely view through monitors. Different people will always have different interpretations of the requirements and the effort needed to adapt to changes. Leaders may not always accept the front-line developers\u0026rsquo; time estimates for requirement changes, influenced by various factors such as client demands or discrepancies in understanding between leaders and developers. Requirement changes invariably bring about significant, hard-to-assess costs, which is one reason the agile model was proposed: to allow for flexible adjustments when requirements change.\nWhen it comes to time estimation, trusting programmers\u0026rsquo; assessments of development time is the most reasonable approach, provided there is mutual trust. However, due to a lack of trust or a desire to see more content developed in a shorter time, some leaders might force programmers to compress development timelines. This might allow the functionality to go live quickly and seemingly work well, but the long-term risks remain known only to the development team. In this industry, every developer is glued to their monitor, typing in code, and leaders cannot immediately judge if the programmers are slacking off. As a result, when leaders encounter a few unprofessional programmers, they might develop a bias against the entire field.\nFrom this perspective, open-source software naturally accepts everyone\u0026rsquo;s code reviews. Even if the main repository does not merge changes, anyone can fork and create a new repository for development, ensuring that hidden risks are eventually uncovered. This is why programmers tend to prefer projects with a high number of stars and a strong, reputable community behind them.\nWei Yan Wouldn\u0026rsquo;t Make a Good \u0026ldquo;Development Manager\u0026rdquo; Returning to the Ziwu Valley Strategy, from a software engineering perspective, it\u0026rsquo;s evident that Wei Yan wanted to change the requirements mid-process (after the army had already been deployed), disregarding development costs (the 5,000 soldiers), and this change could have led to the software crashing (triggering the full wrath of Wei and the fall of Shu). The online discussions surrounding the Ziwu Valley Strategy often stop at \u0026ldquo;what if it succeeded.\u0026rdquo; Perhaps this is why, in software development, leaders always propose \u0026ldquo;unreasonable\u0026rdquo; requirements.\nOf course, we\u0026rsquo;re discussing why, from a software engineering perspective, it\u0026rsquo;s crucial to avoid risky decisions when facing significant and challenging requirement changes. But this isn\u0026rsquo;t absolute. During the Three Kingdoms period, Zhang Liao led his troops to wreak havoc in Sun Quan\u0026rsquo;s camp. In the first two decades of the 21st century, companies that rushed to launch software often made fortunes. From this perspective, what is considered reasonable in software engineering might not be reasonable in real-world scenarios. The team’s ability, the expectations and needs of both parties, the timing of success, and luck are all unpredictable factors. Strictly adhering to software engineering principles might only lead to a downfall like Ma Su losing Jie Ting.\nPerhaps we\u0026rsquo;ve just found a reason for overtime? (Laughs)\n","permalink":"https://windypath.com/en/posts/using_weiyan_strategy_to_analyze_software_possibly/","summary":"\u003cblockquote\u003e\n\u003c/blockquote\u003e\n\u003cp\u003eThe following content is excerpted from the internet.：《魏略》蜀军大将魏延认为，长安守将夏侯楙年少，娇生惯养、怯而无谋。今日假若我魏延领精兵五千，背负粮草五千，直由山道深入，寻秦岭而向东，到达子午再往北行。不过十日就能抵达长安。夏侯楙见我军突然出现，必然乘船而逃。如此一来，长安城内只剩下御史、京兆太守而已。长安北门有散民之谷，足以供应我军粮食。而由东方相会合，需要二十日，届时丞相您在由斜谷赶来，必定可以在此与我会师，这么一来，可以一举平定咸阳以西。\u003c/p\u003e","title":"Discussing the feasibility of software requirements through Wei Yan's \"Ziwu Valley Strategy.\""},{"content":" Introduction: This article aims to introduce the relevant usage of synchronized, ReentrantLock, and Condition in Java.\nLocking with Synchronized Synchronized can be applied to instance methods, static methods, and code blocks. When used to modify a code block, it can either lock on a specific object or on a class (.class).\nSynchronized is a Non-Fair Lock The following code utilizes synchronized to lock on a variable accessible by multiple threads, achieving the orderly printing of numbers. Additionally, it calculates the frequency of number printing for different threads:\npackage com.windypath.lockcondition; public class Syn { int count = 0; final Object sth = new Object(); void play() { int loopTimes = 1000; SynThread t1 = new SynThread(loopTimes, \u0026#34;t1\u0026#34;); SynThread t2 = new SynThread(loopTimes, \u0026#34;t2\u0026#34;); SynThread t3 = new SynThread(loopTimes, \u0026#34;t3\u0026#34;); SynThread t4 = new SynThread(loopTimes, \u0026#34;t4\u0026#34;); t1.start(); t2.start(); t3.start(); t4.start(); } public static void main(String[] args) { Syn syn = new Syn(); syn.play(); } class SynThread extends Thread { int loopTimes; public SynThread(int loopTimes, String threadName) { super(threadName); this.loopTimes = loopTimes; } @Override public void run() { int times = 0; while (count \u0026lt;= 200000) { synchronized (sth) { count++; // System.out.println(getName() + \u0026#34; 输出 \u0026#34; + count); times++; } } System.out.println(getName() + \u0026#34;一共输出了 \u0026#34; + times + \u0026#34; 次\u0026#34;); } } } Output：\nt2一共输出了 103061 次 t1一共输出了 37174 次 t4一共输出了 33751 次 t3一共输出了 26018 次 It can be observed that the number of times thread t2 outputs is more than the sum of the other three threads. This is because synchronized is a non-fair lock.\nSynchronized\u0026rsquo;s Waiting Queue The waiting queue for an object locked with synchronized is located in the _waitSet of the ObjectMonitor. This ObjectMonitor is a low-level native (C/C++) component.\nSynchronized Lock Upgrade However, heavyweight locks are not acquired right from the start. Instead, the optimization begins with biased locking. It only upgrades to lightweight locks in the presence of contention, and only when numerous threads are involved in lock contention does it escalate from a lightweight lock to a heavyweight lock.\nThe locked object uses the MarkWord in its object header to store lock information.\nThe storage structure of a Java object in memory consists of three parts:\nObject header Instance variables Padding bytes Among them, the object header mainly stores some runtime data:\nMarkWord Class Metadata Address (points to the object type data) Array Length (if it\u0026rsquo;s an array, it records the length) The lock information is recorded in the MarkWord of the object header. The following diagram illustrates the different bits of information in the MarkWord for different locks: Biased Lock Biased locking is designed to avoid the resource consumption associated with higher-level locks, such as lightweight locks, when a lock is acquired in a non-multithreaded environment. The term \u0026ldquo;biased\u0026rdquo; means that the locked object is biased toward a specific thread. Its object header stores the ID of the biased thread.\nLightweight Lock The lightweight lock is not intended to replace heavyweight locks. Its purpose is to reduce the performance overhead incurred by traditional heavyweight locks in the absence of multithreaded competition. Before explaining the execution process of the lightweight lock, it\u0026rsquo;s essential to understand that the lightweight lock is suitable for scenarios where threads alternately execute synchronized blocks. Differences Between Lightweight Lock and Biased Lock The process of acquiring a lightweight lock involves multiple CAS (Compare-And-Swap) operations, whereas a biased lock requires only one CAS operation. Lightweight locks are suitable for scenarios where threads alternately execute synchronized blocks. In contrast, biased locks are designed to further improve performance when only one thread executes the synchronized block.\nObservation of Synchronized Lock Escalation Attempt to use an object, and have multiple threads acquire and release a synchronized lock on it at different time intervals to observe its lock state.\nthread1: Acquires and releases immediately.\nthread2: Waits 500ms to acquire, then holds for 1500ms before releasing.\nthread3: Waits 1000ms to acquire, then releases immediately.\nAt this point, there will be lock contention between thread2 and thread3.\nSource Code：\npackage com.windypath; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openjdk.jol.info.ClassLayout; /** * * Observing the process of synchronized transitioning from biased lock to lightweight lock to heavyweight lock. * Using log4j2 */ public class BiasdLock { final static Logger log = LogManager.getLogger(); public static void main(String[] args) throws InterruptedException { log.debug(Thread.currentThread().getName() + \u0026#34;最开始的状态:\\n\u0026#34; + ClassLayout.parseInstance(new Object()).toPrintable()); // After starting, the HotSpot Virtual Machine has a 4-second delay before enabling biased locking mode for each newly created object. Thread.sleep(4000); // 创建一个对象，用于多个不同的线程上锁用 Object obj = new Object(); log.debug(Thread.currentThread().getName() + \u0026#34;等待4秒后的状态（新对象）:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); //线程1，马上上锁马上释放 new Thread(() -\u0026gt; { log.debug( Thread.currentThread().getName() + \u0026#34;开始执行准备获取锁:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); synchronized (obj) { log.debug(Thread.currentThread().getName() + \u0026#34;获取锁执行中:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); } log.debug(Thread.currentThread().getName() + \u0026#34;释放锁:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); }, \u0026#34;thread1\u0026#34;).start(); // 线程2，等线程1释放锁后再上锁 new Thread(() -\u0026gt; { try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } log.debug( Thread.currentThread().getName() + \u0026#34;开始执行准备获取锁:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); synchronized (obj) { log.debug(Thread.currentThread().getName() + \u0026#34;获取锁执行中:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); try { Thread.sleep(1500); } catch (InterruptedException e) { throw new RuntimeException(e); } } log.debug(Thread.currentThread().getName() + \u0026#34;释放锁:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); }, \u0026#34;thread2\u0026#34;).start(); // 线程3，在线程2拥有锁的时候尝试上锁 new Thread(() -\u0026gt; { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } log.debug( Thread.currentThread().getName() + \u0026#34;开始执行准备获取锁:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); synchronized (obj) { log.debug(Thread.currentThread().getName() + \u0026#34;获取锁执行中:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); } log.debug(Thread.currentThread().getName() + \u0026#34;释放锁:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); }, \u0026#34;thread3\u0026#34;).start(); //主线程等待所有线程运行结束，查看状态 Thread.sleep(5000); log.debug(Thread.currentThread().getName() + \u0026#34;结束状态:\\n\u0026#34; + ClassLayout.parseInstance(obj).toPrintable()); } } Output(Briefly):\n15:53:58.436 [main] main最开始的状态:non-biasable 15:54:02.854 [main] 等待4秒后的状态（新对象）:biasable 15:54:02.858 [thread1] thread1开始执行准备获取锁:biasable 15:54:02.858 [thread1] thread1获取锁执行中:biased 15:54:02.859 [thread1] thread1释放锁:biased 15:54:03.367 [thread2] thread2开始执行准备获取锁:biased 15:54:03.368 [thread2] thread2获取锁执行中:thin lock 15:54:03.869 [thread3] thread3开始执行准备获取锁:thin lock 15:54:04.872 [thread3] thread3获取锁执行中:fat lock 15:54:04.872 [thread2] thread2释放锁:fat lock 15:54:04.873 [thread3] thread3释放锁:fat lock 15:54:07.868 [main] main结束状态:non-biasable The following conclusions can be drawn from the analysis:\nFor the HotSpot Virtual Machine, objects created immediately after startup are non-biasable. Objects created after 4 seconds are biasable. When thread1 acquires the lock, as there is only one thread holding the synchronized lock for this object, it transitions to the biased lock state. When thread1 releases the lock, the lock object remains in the biased lock state and does not revert to biasable. After 500ms, when thread2 acquires the lock, the lock object\u0026rsquo;s state is upgraded to a lightweight lock. Another 500ms later, when thread3 also attempts to acquire the lock, its state is lightweight lock (thin lock) until it executes the synchronized block. It then blocks until thread2 releases the lock, at which point it immediately acquires the lock (the timestamps in the third and fourth lines are exactly the same, both 15:54:04.872). Thread3 releases the lock immediately, at this moment, it is still a heavyweight lock. After the main thread waits for 5 seconds, the lock state is restored but becomes non-biasable. You can try commenting out the earlier 4-second delay; in this case, the object would immediately acquire a lightweight lock. Locking with ReentrantLock ReentrantLock is a lightweight, reentrant lock. It can be specified as a fair lock during creation. ReentrantLock can be used in conjunction with Condition. It provides several functions related to concurrent programming, offering higher flexibility compared to synchronized.\nReentrantLock supports whether the lock is fair. In addition to the regular lock() function, ReentrantLock also provides tryLock() for polling and lockInterruptibly() for interruptible locking. After acquiring a lock with ReentrantLock, you can wait on different conditions based on your business logic. ReentrantLock can be used as a fair lock. package com.windypath.lockcondition; import java.util.concurrent.locks.ReentrantLock; public class Reen { int count = 0; final ReentrantLock lock = new ReentrantLock(true); void play() { int loopTimes = 1000; ReenThread t1 = new ReenThread(loopTimes, \u0026#34;t1\u0026#34;); ReenThread t2 = new ReenThread(loopTimes, \u0026#34;t2\u0026#34;); ReenThread t3 = new ReenThread(loopTimes, \u0026#34;t3\u0026#34;); ReenThread t4 = new ReenThread(loopTimes, \u0026#34;t4\u0026#34;); t1.start(); t2.start(); t3.start(); t4.start(); } public static void main(String[] args) { Reen reen = new Reen(); reen.play(); } class ReenThread extends Thread { int loopTimes; public ReenThread(int loopTimes, String threadName) { super(threadName); this.loopTimes = loopTimes; } @Override public void run() { int times = 0; while (count \u0026lt;= 200000) { try { lock.lock(); count++; // System.out.println(getName() + \u0026#34; 输出 \u0026#34; + count); times++; } finally { lock.unlock(); } } System.out.println(getName() + \u0026#34;一共输出了 \u0026#34; + times + \u0026#34; 次\u0026#34;); } } } Output:\nt3一共输出了 49953 次 t4一共输出了 49988 次 t1一共输出了 50077 次 t2一共输出了 49986 次 It can be observed that the output of the four threads is generally around 50,000.\nReentrantLock Simulating the Dining Philosophers Problem Without Using Condition The dining philosophers problem involves five philosophers sitting around a circular table with only five chopsticks. After a philosopher finishes contemplating, they need to simultaneously acquire the chopsticks on their left and right sides to eat.\nHere, we use threads to simulate philosophers and use ReentrantLock to simulate chopsticks.\npackage com.windypath; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class DiningPhilosopher { public static void main(String[] args) { int numPhilosophers = 5; Philosopher[] philosophers = new Philosopher[numPhilosophers]; Chopstick[] chopsticks = new Chopstick[numPhilosophers]; for (int i = 0; i \u0026lt; numPhilosophers; i++) { chopsticks[i] = new Chopstick(); } for (int i = 0; i \u0026lt; numPhilosophers; i++) { Chopstick leftChopstick = chopsticks[i]; Chopstick rightChopstick = chopsticks[(i + 1) % numPhilosophers]; // philosophers[i] = new Philosopher(i, leftChopstick, rightChopstick); if (i % 2 == 0) { philosophers[i] = new Philosopher(i, leftChopstick, rightChopstick); } else { philosophers[i] = new Philosopher(i, rightChopstick, leftChopstick); } Thread thread = new Thread(philosophers[i]); thread.start(); } } static class Philosopher implements Runnable { private final int id; private final Chopstick leftChopstick; private final Chopstick rightChopstick; private int eatTimes = 0; public Philosopher(int id, Chopstick leftChopstick, Chopstick rightChopstick) { this.id = id; this.leftChopstick = leftChopstick; this.rightChopstick = rightChopstick; } private void think() throws InterruptedException { System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; is thinking.\u0026#34;); Thread.sleep((long) ( 1000)); } private void eat() throws InterruptedException { leftChopstick.pickUp(); rightChopstick.pickUp(); System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; picks up both chopsticks and eats.\u0026#34;); Thread.sleep((long) ( 1000)); System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; puts down both chopsticks.\u0026#34;); rightChopstick.putDown(); leftChopstick.putDown(); eatTimes++; if (eatTimes % 10 == 0) { System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; 目前吃了\u0026#34; + eatTimes + \u0026#34;次\u0026#34;); } } @Override public void run() { try { while (true) { think(); eat(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } static class Chopstick { private final Lock lock = new ReentrantLock(); public void pickUp() { lock.lock(); } public void putDown() { lock.unlock(); } } } In the above code, the chopsticks only need to be locked by philosophers when picked up using the lock() function and unlocked when put down using the unlock() function to achieve the goal of \u0026ldquo;simultaneously having the chopsticks on the left and right sides.\u0026rdquo;\nCode Using Condition: package com.windypath; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class DiningPhilosophers { public static void main(String[] args) { int numPhilosophers = 5; Philosopher[] philosophers = new Philosopher[numPhilosophers]; Chopstick[] chopsticks = new Chopstick[numPhilosophers]; for (int i = 0; i \u0026lt; numPhilosophers; i++) { chopsticks[i] = new Chopstick(); } for (int i = 0; i \u0026lt; numPhilosophers; i++) { Chopstick leftChopstick = chopsticks[i]; Chopstick rightChopstick = chopsticks[(i + 1) % numPhilosophers]; // philosophers[i] = new Philosopher(i, leftChopstick, rightChopstick); if (i % 2 == 0) { philosophers[i] = new Philosopher(i, leftChopstick, rightChopstick); } else { philosophers[i] = new Philosopher(i, rightChopstick, leftChopstick); } Thread thread = new Thread(philosophers[i]); thread.start(); } } static class Philosopher implements Runnable { private final int id; private final Chopstick leftChopstick; private final Chopstick rightChopstick; private int eatTimes = 0; public Philosopher(int id, Chopstick leftChopstick, Chopstick rightChopstick) { this.id = id; this.leftChopstick = leftChopstick; this.rightChopstick = rightChopstick; } private void think() throws InterruptedException { System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; is thinking.\u0026#34;); Thread.sleep((long) ( 1000)); } private void eat() throws InterruptedException { leftChopstick.pickUp(); rightChopstick.pickUp(); System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; picks up both chopsticks and eats.\u0026#34;); Thread.sleep((long) ( 1000)); System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; puts down both chopsticks.\u0026#34;); rightChopstick.putDown(); leftChopstick.putDown(); eatTimes++; if (eatTimes % 10 == 0) { System.out.println(\u0026#34;Philosopher \u0026#34; + id + \u0026#34; 目前吃了\u0026#34; + eatTimes + \u0026#34;次\u0026#34;); } } @Override public void run() { try { while (true) { think(); eat(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } static class Chopstick { private final Lock lock = new ReentrantLock(true); private final Condition condition = lock.newCondition(); private boolean taken = false; public void pickUp() throws InterruptedException { lock.lock(); try { while (taken) { condition.await(); } taken = true; } finally { lock.unlock(); } } public void putDown() { lock.lock(); try { taken = false; condition.signal(); } finally { lock.unlock(); } } } } You can see that the Chopstick class has an added taken status to determine whether the chopstick is currently possessed by a philosopher. When the first philosopher picks up a chopstick, taken becomes true, and the lock is released. When the second philosopher picks up the same chopstick, they still acquire the same lock but enter a waiting state with condition.await() due to taken being true. At this point, the lock is also released, allowing other philosophers to pick up this chopstick.\nWhen the chopstick is put down, the signal() method is called, and the thread waiting at the previous await() function is awakened, allowing it to execute its subsequent logic.\nIf a fair lock is not used, you might see that two philosophers eat very late in their 10 cycles. With a fair lock, almost all five philosophers synchronize and complete their 10 cycles.\nNote that when initializing philosophers, chopsticks for philosophers with odd numbers are swapped. This is because in the subsequent logic for picking up chopsticks, we always pick up the left chopstick first and then the right one. If we don\u0026rsquo;t reverse the hands for some philosophers, there would be a situation where all five philosophers pick up the left chopstick simultaneously and then wait for the right one, leading to a deadlock. (Of course, we could also use random numbers to let philosophers decide whether to pick up the left or right chopstick first.)\n","permalink":"https://windypath.com/en/posts/java_juc_briefly/","summary":"\u003cblockquote\u003e\n\u003cp\u003eIntroduction: This article aims to introduce the relevant usage of synchronized, ReentrantLock, and Condition in Java.\u003c/p\u003e\n\u003c/blockquote\u003e","title":"Various Locking Mechanisms in Java Concurrency Programming"},{"content":"Preface During a coding interview, I encountered a question that involved two lines of input. Each line contained an unknown number of numbers separated by spaces. The input format was as follows:\n12 34 567 888 99 100 358 74 58454 742 4469 88 They did not provide the number of digits in each line in advance. Instead, they required the user to split them themselves.\nDuring the coding exam, I didn\u0026rsquo;t implement this functionality using C++, but instead used the split() method available in Java to handle it.\nLater, after the exam was over, I searched online for ways to split strings in C++, and I found that C++ does not have a built-in method similar to split(character) like in Java.\nSo, what methods can be used as alternatives?\nMethod 1: Splitting using string\u0026rsquo;s find() function along with substr() According to the response from a Zhihu user, the first solution they suggested is:\nC++ 的 string 为什么不提供 split 函数？ - 知乎用户的回答 - 知乎 https://www.zhihu.com/question/36642771/answer/865135551\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;cstring\u0026gt; #include \u0026lt;vector\u0026gt; void split(const std::string\u0026amp; s, std::vector\u0026lt;std::string\u0026gt;\u0026amp; tokens, const std::string\u0026amp; delimiters = \u0026#34; \u0026#34;) { std::string::size_type lastPos = s.find_first_not_of(delimiters, 0); std::string::size_type pos = s.find_first_of(delimiters, lastPos); while (std::string::npos != pos || std::string::npos != lastPos) { tokens.push_back(s.substr(lastPos, pos - lastPos)); lastPos = s.find_first_not_of(delimiters, pos); pos = s.find_first_of(delimiters, lastPos); } } int main() { std::string str = \u0026#34;12 34 567 888 99 100\u0026#34;; std::vector\u0026lt;std::string\u0026gt; res; split(str, res, \u0026#34; \u0026#34;); for (auto r: res) { printf(\u0026#34;%s\\n\u0026#34;, r.c_str()); } return 0; } The output is：\n12 34 567 888 99 100 The split() function works by keeping track of two indices to determine the substrings to be extracted:\nThe first index, lastPos, finds the index of the first character after the start of the string that is not a delimiter. The second index, pos, finds the index of the first character after lastPos that is a delimiter. By doing this, the substring between lastPos and pos is the portion of the string that needs to be extracted. After extracting the first substring, both indices are moved forward according to the previous logic, until both indices cannot find suitable values (returning string::npos). This marks the end of the process.\nFunction Introduction: find_first_of() The find_first_of() function of string takes two parameters. The first parameter is the character to search for, which can be a string, char*, or char. The second parameter is the index to start searching from (it is optional and defaults to 0). It searches from the specified index onward until it finds the character being searched for, and then returns the index where the character is found.\nfind_first_not_of() The find_first_not_of() function of string accepts the same parameters as find_first_of(). However, it searches until it encounters a character that is not in the search characters. It returns the index of the first character that is not part of the search characters.\nsubstr() The substr() function is used to extract a substring from a string. It takes two parameters, pos and len, indicating the starting position and the length of the substring to be extracted. The original string is not modified.\nC++ document location：\nfind_first_of()：https://cplusplus.com/reference/string/string/find_first_of/\nfind_first_not_of()：https://cplusplus.com/reference/string/string/find_first_not_of/\nsubstr()：https://cplusplus.com/reference/string/string/substr/\nMethod 2：C++11 regular expression #include \u0026lt;iostream\u0026gt; #include \u0026lt;vector\u0026gt; #include \u0026lt;regex\u0026gt; int main() { std::string str = \u0026#34;12 34 567 888 99 100\u0026#34;; std::regex ws_re(\u0026#34;\\\\s+\u0026#34;); std::vector\u0026lt;std::string\u0026gt; res( std::sregex_token_iterator( str.begin(), str.end(), ws_re, -1 ), std::sregex_token_iterator() ); for (auto r: res) { printf(\u0026#34;%s\\n\u0026#34;, r.c_str()); } return 0; } This example comes from the introduction to regex token iterator.\nhttps://en.cppreference.com/w/cpp/regex/regex_token_iterator\nUsing the sregex_token_iterator() iterator for splitting operations (where s refers to a string type). In this example, in lines 9-11, a sregex_token_iterator iterator is constructed with four parameters: the iterator to the beginning of the string, the iterator to the end of the string, a regular expression object, and whether to use the matched parts (0 for using, -1 for not using).\nBy constructing the sregex_token_iterator(), it is determined to start searching from the beginning of the string and continue until the end of the string, using regular expression matching, and finding the unmatched parts.\nThe end of this iterator is represented by a default-constructed sregex_token_iterator() object.\nIn the constructor of vector, by passing in two iterators, the elements between the iterators can be obtained.\nMethod 3: Splitting strings using stringstream (supports only space, newline, tab) Source：https://www.cnblogs.com/narjaja/p/10044157.html\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;sstream\u0026gt; #include \u0026lt;vector\u0026gt; int main() { std::string str = \u0026#34;12 34 567 888 99 100\u0026#34;; std::vector\u0026lt;std::string\u0026gt; res; std::istringstream ss(str); std::string word; while(ss\u0026gt;\u0026gt;word) { res.push_back(word); } for (auto r: res) { printf(\u0026#34;%s\\n\u0026#34;, r.c_str()); } return 0; } By using the \u0026raquo; operator in C++, similar to how cin works for user input, we can \u0026ldquo;input\u0026rdquo; a string and achieve the splitting effect.\nIf you want to support custom delimiters, you can use getline() for handling.\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;sstream\u0026gt; #include \u0026lt;vector\u0026gt; using namespace std; int main() { std::string data = \u0026#34;1_2_3_4_5_6\u0026#34;; std::stringstream ss(data); std::string item; cout \u0026lt;\u0026lt; data \u0026lt;\u0026lt; endl; while (std::getline(ss, item, \u0026#39;_\u0026#39;)) cout \u0026lt;\u0026lt; item \u0026lt;\u0026lt; \u0026#39; \u0026#39;; } Method 4: Implementing with the C function strtok() The first incorrect approach Another approach is to use the strtok() function from C language for handling the string splitting.\nOn the internet, you may come across code structures similar to the following:\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;cstring\u0026gt; int main() { char str[] = \u0026#34;A B C D\u0026#34;; char* p = strtok(str, \u0026#34; \u0026#34;); std::cout \u0026lt;\u0026lt; p \u0026lt;\u0026lt; std::endl; while (p != NULL) { p = strtok(NULL, \u0026#34; \u0026#34;); std::cout \u0026lt;\u0026lt; p \u0026lt;\u0026lt; std::endl; } return 0; } The output is：\nA B C D However, when I attempted to perform a cout output on line 11, I found that the result was not displayed correctly:\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;cstring\u0026gt; int main() { char str[] = \u0026#34;A B C D\u0026#34;; char* p = strtok(str, \u0026#34; \u0026#34;); std::cout \u0026lt;\u0026lt; p \u0026lt;\u0026lt; std::endl; while (p != NULL) { p = strtok(NULL, \u0026#34; \u0026#34;); std::cout \u0026lt;\u0026lt; p \u0026lt;\u0026lt; std::endl; } std::cout \u0026lt;\u0026lt; \u0026#34;abc\u0026#34; \u0026lt;\u0026lt; std::endl; return 0; } The output is：\nA B C D The final \u0026ldquo;abc\u0026rdquo; is missing in the output。\nAfter consulting with ChatGPT, the explanation received is as follows:\nThe issue in this C++ code is that when iterating and outputting the split substrings, the value of p is printed first before proceeding to the next iteration. This causes the value of p to be set as NULL after the last iteration, and then attempting to print the value of p leads to undefined behavior.\nIn line 8, you print the value of p and then in line 9, it is set to the next split substring. Then, in line 10, when the loop begins again, you print the value of p again, but at this point, it may already be NULL, resulting in undefined behavior.\nTo fix this issue, you can move the printing statement to the end of the loop, so that the value of p is printed after proceeding to the next iteration, ensuring that p is not NULL.\nHere is the corrected code:\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;cstring\u0026gt; int main() { char str[] = \u0026#34;A B C D\u0026#34;; char* p = strtok(str, \u0026#34; \u0026#34;); while (p != NULL) { std::cout \u0026lt;\u0026lt; p \u0026lt;\u0026lt; std::endl; p = strtok(NULL, \u0026#34; \u0026#34;); } std::cout \u0026lt;\u0026lt; \u0026#34;abc\u0026#34; \u0026lt;\u0026lt; std::endl; return 0; } After making this modification, the code will correctly output the split substrings and then output \u0026ldquo;abc\u0026rdquo;. Please note that std::endl is used to add a newline character after the output to ensure the correct formatting of the output result.\nThe second incorrect approach #include \u0026lt;stdio.h\u0026gt; #include\u0026lt;string.h\u0026gt; int main() { char s[] = \u0026#34;A B C D\u0026#34;; char *p; const char *d = \u0026#34; \u0026#34;; p = strtok(s, d); while(p) { printf(\u0026#34;%s\\n\u0026#34;, p); p = strtok(NULL, \u0026#34; \u0026#34;); } printf(\u0026#34;abc\u0026#34;); return 0; } This time, we output the previous split p first within the loop body and then read the next p. However, the string \u0026ldquo;abc\u0026rdquo; still doesn\u0026rsquo;t output correctly. Here\u0026rsquo;s ChatGPT\u0026rsquo;s answer:\nChatGPT:\nThe reason why \u0026ldquo;abc\u0026rdquo; cannot be output correctly in this code is that when using the strtok function to split the string, it replaces the delimiter in the original string with a null character \u0026lsquo;\\0\u0026rsquo; to separate the substrings. This modification alters the original string s, and subsequent printf statements will terminate prematurely when encountering \u0026lsquo;\\0\u0026rsquo;.\nIn the code, the content of the original string s is \u0026ldquo;A B C D\u0026rdquo;, and strtok(s, d) will split it into four substrings: \u0026ldquo;A\u0026rdquo;, \u0026ldquo;B\u0026rdquo;, \u0026ldquo;C\u0026rdquo;, and \u0026ldquo;D\u0026rdquo;. Therefore, the printf statement in the loop will output these four substrings: \u0026ldquo;A\u0026rdquo;, \u0026ldquo;B\u0026rdquo;, \u0026ldquo;C\u0026rdquo;, and \u0026ldquo;D\u0026rdquo;.\nThen, in the last call to strtok(NULL, \u0026quot; \u0026ldquo;), since there are no more delimiters, strtok will return NULL and terminate the loop. Subsequently, the printf(\u0026ldquo;abc\u0026rdquo;) statement in the code will attempt to output \u0026ldquo;abc\u0026rdquo;. However, due to the previous strtok calls modifying the original string s and replacing the spaces with \u0026lsquo;\\0\u0026rsquo;, when reaching the printf statement, the function encounters the \u0026lsquo;\\0\u0026rsquo; character, treating it as the end of the string and causing the output to terminate prematurely.\nIf you want to output \u0026ldquo;abc\u0026rdquo;, you can add a newline character \\n to the printf statement as shown below:\n#include \u0026lt;stdio.h\u0026gt; #include \u0026lt;string.h\u0026gt; int main() { char s[] = \u0026#34;A B C D\u0026#34;; char *p; const char *d = \u0026#34; \u0026#34;; p = strtok(s, d); while (p) { printf(\u0026#34;%s\\n\u0026#34;, p); p = strtok(NULL, \u0026#34; \u0026#34;); } printf(\u0026#34;abc\\n\u0026#34;); // 在\u0026#34;abc\u0026#34;后添加换行符\\n return 0; } With the above modification, the code will be able to output \u0026ldquo;A\u0026rdquo;, \u0026ldquo;B\u0026rdquo;, \u0026ldquo;C\u0026rdquo;, \u0026ldquo;D\u0026rdquo;, and \u0026ldquo;abc\u0026rdquo; correctly.\nstrtok() Function After the strtok() function performs the splitting, it fills the cut positions with \u0026lsquo;\\0\u0026rsquo;, thereby modifying the original string. Therefore, it is essential to exercise caution and use this function carefully. 通过上述修改，代码将能够正常输出\u0026quot;A\u0026rdquo;、\u0026ldquo;B\u0026rdquo;、\u0026ldquo;C\u0026rdquo;、\u0026ldquo;D\u0026quot;和\u0026quot;abc\u0026rdquo;。 strtok()函数\n","permalink":"https://windypath.com/en/posts/how_to_split_a_string_in_cpp/","summary":"\u003ch1 id=\"preface\"\u003ePreface\u003c/h1\u003e\n\u003cp\u003eDuring a coding interview, I encountered a question that involved two lines of input. Each line contained an unknown number of numbers separated by spaces. The input format was as follows:\u003c/p\u003e\n\u003cpre tabindex=\"0\"\u003e\u003ccode\u003e12 34 567 888 99 100\n358 74 58454 742 4469 88\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eThey did not provide the number of digits in each line in advance. Instead, they required the user to split them themselves.\u003c/p\u003e\n\u003cp\u003eDuring the coding exam, I didn\u0026rsquo;t implement this functionality using C++, but instead used the split() method available in Java to handle it.\u003c/p\u003e\n\u003cp\u003eLater, after the exam was over, I searched online for ways to split strings in C++, and I found that C++ does not have a built-in method similar to split(character) like in Java.\u003c/p\u003e\n\u003cp\u003eSo, what methods can be used as alternatives?\u003c/p\u003e","title":"How To Split A String In C++?"},{"content":"Welcome Hello and welcome to WindyPath. I am the owner of this website. My English name is Johnathan.\nMy Chinese nickname is \u0026ldquo;凌虚\u0026rdquo; which comes from a Chinese animated film called The Legend of Qin. \u0026ldquo;凌虚\u0026rdquo; is the name of a sword that belong to Zhang Liang(张良), a famous strategist in the Warring Period. The name of this website is WindyPath, and its Chinese name is \u0026ldquo;风萧古道\u0026rdquo;.\nThe first two characters, \u0026ldquo;风萧\u0026rdquo; come from poetry \u0026ldquo;风萧萧兮易水寒\u0026rdquo; while the last two characters, \u0026ldquo;古道\u0026rdquo; are derived from poetry \u0026ldquo;古道西风瘦马\u0026rdquo;.\nAbout Me I work as a Game Server Engineer and I have previously developed website, including both frontend and backend. However, I no longer develop websites.\nI graduated from university in 2019, and I moved to ShangHai in December 2020.\nYou can read more about my computer story HERE.\nMy Idealism For a long time, I didn\u0026rsquo;t know what to study software development for. I have earned some money in these years, but I wanted to move forward in my career of software development. I am interested in developing Chinese software.\nFor Chinese Software My Articles I do not update my blog frequently, but I do browse articles on other blogs. I have noticed that some blogs have many articles that are little more than complaints or notes. These types of articles do not effectively improve software development.\nOn my blog, I only publish technology articles. Even if I feel compelled to complain about something, I always try to tie it back to a software development concept so that visitors can learn something from it.\nI post other daily life observations and complaints on my Twitter account.\nContact Email: windypathblog@gmail.com Telegram: @windypath\n","permalink":"https://windypath.com/en/posts/about_myself/","summary":"\u003ch1 id=\"welcome\"\u003eWelcome\u003c/h1\u003e\n\u003cp\u003eHello and welcome to WindyPath. I am the owner of this website. My English name is Johnathan.\u003c/p\u003e\n\u003cp\u003eMy Chinese nickname is \u0026ldquo;凌虚\u0026rdquo; which comes from a Chinese animated film called \u003cem\u003eThe Legend of Qin\u003c/em\u003e. \u0026ldquo;凌虚\u0026rdquo; is the name of a sword that belong to Zhang Liang(张良), a famous strategist in the Warring Period. The name of this website is \u003cem\u003eWindyPath\u003c/em\u003e, and its Chinese name is \u0026ldquo;风萧古道\u0026rdquo;.\u003c/p\u003e\n\u003cp\u003eThe first two characters, \u0026ldquo;风萧\u0026rdquo; come from poetry \u0026ldquo;风萧萧兮易水寒\u0026rdquo; while the last two characters, \u0026ldquo;古道\u0026rdquo; are derived from poetry \u0026ldquo;古道西风瘦马\u0026rdquo;.\u003c/p\u003e","title":"My Self-introduction"},{"content":"Click here to download my virtual machine image Download virtual machine image:\nLink：https://pan.baidu.com/s/1yfY0SjDrtOeuTiEWf7YizA?pwd=374l\nFetch Code：374l\nMy VirtualBox version is 6.1\nLet me talk about nostalgic For most people, Win95 is their youth, so they create UI component library React95, or create an OS serenity together. But for most Chinese people, when they got PC in 2000-2010, they used Windows XP in their PC.\nsh1zuku is from China, Taiwan, he created a Windows XP simulator on website: Project Link, Online Demo, and another programmer from Vietnam wrote a Windows 7 Simulator on website Online Demo.\nHonestly, I don\u0026rsquo;t have enough ability to develop simulator program like them, but I have an idea that I can install a Windows XP virtual machine on my PC.\nThe steps you might choose Install VirtualBox. Download Image: Find Windows XP Image in MSDN Itellyou and then download it. Install the Image in VirtualBox. Run the installed image, and install the OS. Then, you will discover that the Windows XP only has 30-day trail. In the early 2000s, piracy was rampant, and Microsoft took strong measures to limit it. Even if you enter the correct serial number when you install, Microsoft will ask you to activate using a phone, etc.\nBut I just want to experienct the old OS in my PC! (It\u0026rsquo;s too hard for me to activate a copyrighted WinXP!)\nThe Right Solution So I don\u0026rsquo;t use this copyrighted WinXP image anymore, I should search some WinXP image without activation.\nHere, I found github WinXPImage from Github, but his Image file saved on Google Drive. I have downloaded that and uploaded to Baidu Cloud:\nLink：https://pan.baidu.com/s/1ypKeaZixJXnbqAo4ZT0YLQ?pwd=30dd Fetch Code：30dd\nWhen you install this image on VirtualBox, you will get a WinXP(English Edition) that you can use indefinitely.\nBut you may not be able to start this Image successfully, you should execute this after importing the OVA File:\nvbox-img geometry --filename Windows_XP_Professional-disk1.vdi --format VDI --cylinders 5874 --heads 255 --sectors 56 From github issue streeg\u0026rsquo;s solution.\nHow to Chinesize Windows XP? I want to use Chinese Windows XP to reminisce about the past, but this image doesn\u0026rsquo;t have Chinese language support.\nAfter searching many source, I finally found a language package mui_win_xp_pro_n_cd1 in here.\nI downloaded it and uploaded to Baidu Cloud:\nLink：https://pan.baidu.com/s/18mW9OCRejMDoEpUcih-zlA?pwd=peu4\nFetch Code：peu4\nThen,\nConfigure share folder in Windows XP virtual machine. Source Transfer mui_win_xp_pro_n_cd1.iso to Windows XP virtual machine by share folder. Install it, Source Finally, reboot Windows XP virtual machine.\nScreenshot: ","permalink":"https://windypath.com/en/posts/nostalgic_winxp/","summary":"\u003ch1 id=\"click-here-to-download-my-virtual-machine-image\"\u003eClick here to download my virtual machine image\u003c/h1\u003e\n\u003cp\u003eDownload virtual machine image:\u003c/p\u003e\n\u003cp\u003eLink：https://pan.baidu.com/s/1yfY0SjDrtOeuTiEWf7YizA?pwd=374l\u003c/p\u003e\n\u003cp\u003eFetch Code：374l\u003c/p\u003e\n\u003cp\u003eMy VirtualBox version is 6.1\u003c/p\u003e","title":"Windows XP Virtual Machine Chinese Version Without Activation Image Download"},{"content":"Just Some Usage and features on Java TreeSet. :-)\nAn Example (kotlin) import java.util.TreeSet /** * Define a data class to test TreeSet Collection * Sort by TreeSet * id: player id * score: player score */ data class PlayerScore(var id: Int, var score: Int): Comparable\u0026lt;PlayerScore\u0026gt; { override fun compareTo(other: PlayerScore): Int { return if (score \u0026gt; other.score) { 1 } else if (score \u0026lt; other.score) { -1 } else { 0 } } } fun main() { //create a TreeSet val treeSet: TreeSet\u0026lt;PlayerScore\u0026gt; = TreeSet() //create 3 PlayerScore object，and use \u0026#39;id101Obj\u0026#39; reference to the first obj //put these objects into the treeset val id101Obj = PlayerScore(101,100) //put in different order treeSet.add(PlayerScore(102,200)) treeSet.add(id101Obj) treeSet.add(PlayerScore(103,300)) println(\u0026#34;Add the objects in a different order and print out by score from smallest to largest:\u0026#34;) showTreeSet(treeSet) println(\u0026#34;Add an object with duplicated id but different score, and print out by score from smallest to largest:\u0026#34;) treeSet.add(PlayerScore(101,500)) showTreeSet(treeSet) println(\u0026#34;Change the score of the object whose id is 101 to 400， and print out by score from smallest to largest:\u0026#34;) id101Obj.score = 400 showTreeSet(treeSet) } private fun showTreeSet(treeSet: TreeSet\u0026lt;PlayerScore\u0026gt;) { treeSet.forEachIndexed { index, s -\u0026gt; println(\u0026#34;rank:${index+1} score:${s.score} id:${s.id}\u0026#34;) } println() } Console output:\nAdd the objects in a different order and print out by score from smallest to largest: rank:1 score:100 id:101 rank:2 score:200 id:102 rank:3 score:300 id:103 Add an object with duplicated id but different score, and print out by score from smallest to largest: rank:1 score:100 id:101 rank:2 score:200 id:102 rank:3 score:300 id:103 rank:4 score:500 id:101 Change the score of the object whose id is 101 to 400， and print out by score from smallest to largest: rank:1 score:400 id:101 rank:2 score:200 id:102 rank:3 score:300 id:103 rank:4 score:500 id:101 Analysis First, PlayerScore implements Comparable interface , implements the function of sorting from smallest to largest. If there are only three data pieces at the beginning, insert them in different order, treeset does sort normally.\nThen, when player 101 score was changed, we need to resort. We tried 2 ways to resort.\nChange id101Obj\u0026rsquo;s score by reference. Add a new obj which id is 101 and has a new score into treeset. Result:\nid101Obj\u0026rsquo;s score was changed, but its rank is still 1. Although the score is sorted, it has two objects which id is 101. So how to resort treeset when player\u0026rsquo;s score was changed?\nOne solution is that you can remove the object from treeset, and change its score, then add it to treeset. This is because the underlying TreeSet is a red-black tree, and the tree structure is adjusted when it is deleted and inserted.\nCode:\n//create a TreeSet val treeSet: TreeSet\u0026lt;PlayerScore\u0026gt; = TreeSet() //create 3 PlayerScore object，and use \u0026#39;id101Obj\u0026#39; reference to the first obj //put these objects into the treeset val id101Obj = PlayerScore(101,100) //put in different order treeSet.add(PlayerScore(102,200)) treeSet.add(id101Obj) treeSet.add(PlayerScore(103,300)) println(\u0026#34;Add the objects in a different order and print out by score from smallest to largest:\u0026#34;) showTreeSet(treeSet) treeSet.remove(id101Obj) id101Obj.score = 400 treeSet.add(id101Obj) println(\u0026#34;remove id101Obj from TreeSet，change score，and then add to treeSet中， print out by score from smallest to largest:\u0026#34;) showTreeSet(treeSet) Console output:\nAdd the objects in a different order and print out by score from smallest to largest: rank:1 score:100 id:101 rank:2 score:200 id:102 rank:3 score:300 id:103 remove id101Obj from TreeSet，change score，and then add to treeSet中， print out by score from smallest to largest: rank:1 score:200 id:102 rank:2 score:300 id:103 rank:3 score:400 id:101 Move Forward The solution that \u0026ldquo;Remove it, edit it, and add it\u0026rdquo; can finish resort, but treeSet is thread-unsafe. If there are many threads update player\u0026rsquo;s score, it might be cause some problems.\nAlthough TreeSet can sort as it inserts, it only allow insert once. The modification of the score after insertion does not change the sorting.\nTreeSet doesn\u0026rsquo;t make sense for rank list that move around a lot.\nAnother Rank List Solution I use TreeSet because it can sort as it inserts, but it\u0026rsquo;s not appropriate for a rank list.\nSo, if So another way to think about it is, if you only use a longer ArrayList to store the player\u0026rsquo;s score object, you also sort it on insert/update/delete?\nInsert/update/delete, modify the data in the ArrayList, and then sort.\n","permalink":"https://windypath.com/en/posts/about_java_treeset/","summary":"\u003cp\u003eJust Some Usage and features on Java TreeSet. :-)\u003c/p\u003e","title":"Some Usage and features on Java TreeSet"},{"content":" This article primarily introduces the basics of Linux C++ Socket network programming. Most of the knowledge is sourced from the website: https://www.geeksforgeeks.org/socket-programming-cc/\nSocket Programming State Diagram From the diagram, we can see that the server side needs to go through four steps to enter the \u0026ldquo;waiting for connection\u0026rdquo; state, while the client side only requires two.\nBrief Analysis of Socket Programming Functions This analysis is for personal understanding and may have some omissions. If there are any, please correct them. The original article summarizes the knowledge better than I do. Please refer to the original article as much as possible. My understanding is only for auxiliary purposes.\nServer Let\u0026rsquo;s start with the server. The server needs to specify a port and listen, so it needs to use bind() to bind the port, use listen() to enter the listening state, and then use accept() to block and wait for messages from the client.\nC++ including:\n#include \u0026lt;sys/socket\u0026gt; socket() setsockopt() bind() listen() accept() #include \u0026lt;netinet/in.h\u0026gt; struct sockaddr_in #include \u0026lt;unistd.h\u0026gt; read() #include \u0026lt;arpa/inet.h\u0026gt; inet_pton() socket() This function is used to create a socket. Among the three parameters, the first two are particularly important. It returns a socket number, which is an integer value.\nint sockfd = socket(domain, type, protocol)\ndomain: Use AF_INET for IPv4, and AF_INET6 for IPv6. type: Use SOCK_STREAM for TCP, and SOCK_DGRAM for UDP.\nsetsockopt() This function is used to set properties for the socket returned by the socket() function above. As a server, for convenience, you can set the options for address and port reuse.\nint setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen);\nTo reuse the address and port, you need to do the following:\nSet level to SOL_SOCKET, which represents which module the property value you are setting is for. Set optname to SO_REUSEADDR|SO_REUSEPORT, which means you intend to set both of these properties at the same time. optval should be a pointer to an int, pointing to a specific number. optlen should be sizeof() of the above optval. Many C++ socket functions require you to pass a length to determine how long the data you really want to pass to this function is.\nsockaddr_in So how is an address represented in socket programming? It\u0026rsquo;s defined using struct sockaddr_in.\nWhen using it, you need to set three values: sin_family, sin_addr.s_addr, and sin_port.\nsin_family: Same as the domain parameter in the socket() function, it\u0026rsquo;s AF_INET. sin_addr.s_addr: This property converts our dotted decimal IP address into a number, and it requires a dedicated function for processing, such as inet_pton(). sin_port: Specifies the port number, but it\u0026rsquo;s not directly passed as an integer. You need to use htons() to convert it into a hexadecimal number. bind() This function is used to bind address information to a socket.\nIn the previous section, we discussed how to set up the address. In this section, we\u0026rsquo;ll talk about binding the socket with an address.\nint bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\nAs usual, associate sockFd with the address.\nNote: The type of addr here is struct sockaddr *, not struct sockaddr_in *. The structure of struct sockaddr does not provide properties to hold the IP address and port number, so you need to use struct sockaddr_in for type casting. In the documentation, the author mentions that the lengths of struct sockaddr and struct sockaddr_in must be the same, so you can definitely perform the type casting without worry. https://www.gta.ufrj.br/ensino/eel878/sockets/sockaddr_inman.html Note that addrlen later is a value, not a pointer.\nlisten() int listen(int sockfd, int backlog);\nThis function switches the socket to passive mode, entering the listening state. The second parameter backlog specifies the maximum length of the message waiting queue.\naccept() int new_socket= accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); After this function is executed, the socket will wait for a client connection. Once the connection is established, it returns a new socket for communication between the client and server.\nNote: The third parameter socklen_t *addrlen of accept() is different from the third parameter socklen_t addrlen of bind(). accept() requires a pointer. Some say that the parameter of accept() is a bidirectional parameter and will update the length value of the address. However, others say that in the accept() function, it doesn\u0026rsquo;t know if an int can hold this length. If the length is particularly large, it might not be suitable for storage. To ensure a uniform storage structure, just pass a pointer.\nsend() send() is used to send messages to the other party through the socket.\nread() The read() function is included in #include \u0026lt;unistd.h\u0026gt;. It uses a char array to store the received message.\nClient Now let\u0026rsquo;s talk about the client. The client needs to specify the IP address and port number, and then initiate the connection.\nconnect() int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);\nThe client also needs to create a socket, specify sockaddr_in, and then typecast. This socket is responsible not only for initiating the connection but also for sending and receiving data.\nSample Code (Without Error Handling) Currently, I only want to learn these low-level socket APIs, so I don\u0026rsquo;t want to spend too much effort on memorizing what the return values of the APIs might indicate in terms of errors. I just want to focus on successfully implementing a very basic server and client.\nServer-side Code: server.cpp\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;sys/socket.h\u0026gt; #include \u0026lt;netinet/in.h\u0026gt; #include \u0026lt;unistd.h\u0026gt; #include \u0026lt;string.h\u0026gt; using namespace std; #define PORT 8000 int main() { int sockFd, newSockFd, valread; int opt = 1; char buffer[1024] = {0}; char* helloFromServer = \u0026#34;hello from server\u0026#34;; struct sockaddr_in address; sockFd = socket(AF_INET, SOCK_STREAM, 0); setsockopt(sockFd, SOL_SOCKET, SO_REUSEADDR|SO_REUSEPORT, \u0026amp;opt, sizeof(opt)); address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); int addrlen = sizeof(address); bind(sockFd, (struct sockaddr*)\u0026amp;address, addrlen); listen(sockFd, 3); newSockFd = accept(sockFd, (struct sockaddr*)\u0026amp;address, (socklen_t*)\u0026amp;addrlen); read(newSockFd, buffer, 1024); printf(\u0026#34;receive: %s\\n\u0026#34;, buffer); send(newSockFd, helloFromServer, strlen(helloFromServer), 0); printf(\u0026#34;server sent message\\n\u0026#34;); return 0; } Client-side Code: client.cpp\n#include \u0026lt;iostream\u0026gt; #include \u0026lt;sys/socket.h\u0026gt; #include \u0026lt;netinet/in.h\u0026gt; #include \u0026lt;arpa/inet.h\u0026gt; #include \u0026lt;unistd.h\u0026gt; #include \u0026lt;string.h\u0026gt; #define PORT 8000 using namespace std; int main() { int sockFd = 0; char buffer[1024] = {0}; char* helloFromClient = \u0026#34;hello from client\u0026#34;; struct sockaddr_in address; address.sin_family = AF_INET; inet_pton(AF_INET, \u0026#34;127.0.0.1\u0026#34;, \u0026amp;address.sin_addr.s_addr); address.sin_port = htons(PORT); sockFd = socket(AF_INET, SOCK_STREAM, 0); connect(sockFd, (struct sockaddr*)\u0026amp;address, sizeof(address)); send(sockFd, helloFromClient, strlen(helloFromClient), 0); printf(\u0026#34;client sent\\n\u0026#34;); read(sockFd, buffer, 1024); printf(\u0026#34;read message:%s\\n\u0026#34;, buffer); return 0; } Compilation, Execution, and Targeted Output In the Linux command line, input the following separately:\ng++ -o server server.cpp g++ -o client client.cpp Then open two terminals, and input the following respectively:\n./server ./client The expected outputs are:\nFor the server:\nreceive: hello from client server sent message client输出：\nclient sent message receive: hello from server ","permalink":"https://windypath.com/en/posts/linux_socket_programming/","summary":"\u003cblockquote\u003e\n\u003cp\u003eThis article primarily introduces the basics of Linux C++ Socket network programming.\nMost of the knowledge is sourced from the website: \u003ca href=\"https://www.geeksforgeeks.org/socket-programming-cc/\"\u003ehttps://www.geeksforgeeks.org/socket-programming-cc/\u003c/a\u003e\u003c/p\u003e\n\u003c/blockquote\u003e","title":"Linux C++ Socket in Action"},{"content":" Project Intelligent Customer Service Web Crawler SLG Game Language Java Python Kotlin Model Asynchronous Event Driven There may not be a discernible model Actor Model Transmission Protocol HTTP HTTP TCP + Netty Transmission Structure JSON JSON Protobuf Database Oracle, Redis MongoDB MySQL, Redis Database Framework MyBatis Python Library (similar to JDBC) Hibernate Cache Architecture Redis for Admin Login Status Possibly only caching page numbers All game data is cached, periodically written to the database Configuration Information Only application.properties config.ini Zookeeper, pre-loading design table information into ZK Concurrency No concurrency (so no need for locks) Python multi-threading for simultaneous web crawling No concurrency, Actor model ensures only one task at a time Hot Reload Directly restart N/A Inherit a method from a certain class, replace the online class Architecture Overview Intelligent Customer Service Server Overall Architecture Deployment of Soldiers in SLG Game Typical Case Intelligent Customer Service Chat graph LR A[Client]--\u003e|HTTP chat message|B[Intelligent Customer Service System]--\u003e|Place chat message in message queue|C[Intelligent Q\u0026A Model]--\u003e|Record Q\u0026A information|D[Oracle Database] Deployment of Soldiers in SLG Game graph LR A[Client]--\u003e|Protobuf sent via TCP|B[Gate's Netty Unpacking]--\u003e|Internal message forwarding in actor|C[WorldActor verifies various states of the outer city sand table]--\u003e|Internal message forwarding in actor|D[PlayerActor verifies and retrieves buffs in the inner city] Both WorldActor and PlayerActor retrieve the required data by reading from memory, and do not directly read from the MySQL database. The data in memory is updated to MySQL using Hibernate methods for changes every certain period of time (around 30 seconds).\nConfiguration Information Loading For the intelligent customer service, due to low concurrency and business volume (because there are relatively few platforms for deployment, and almost no one uses it in the early morning, and the restart speed is very fast), some configuration values on demand (such as how many times \u0026ldquo;transfer to human\u0026rdquo; needs to be sent before entering the human transfer channel) are hard-coded directly into the business logic. Some configuration information, such as the request address URLs of other systems, will be placed in application.properties. Excel is not used to centrally store configuration information for various functional modules, and it is indeed not necessary.\nHowever, for the game, configuration values are crucial, closely related to gameplay, rewards, and the in-game ecosystem. Therefore, in the game server, almost all values need to be read from the configuration table. Currently, Excel is probably the most powerful software for handling data, and designers can quickly set up values through Excel.\nWhen starting the server, you need to read the configuration table into memory (in a broad sense). However, with tools like Zookeeper, configuration table data can be stored in ZK and retrieved when needed.\nAdvantages of Game Servers Transmission Structure is Protobuf The data received and sent by the server are all in binary format converted from ProtoBuf, thereby achieving a unified transmission structure between the client and server. ProtoBuf has its own functionality for encoding and decoding binary data, which minimizes the size of message data. Encoding and decoding are executed by Netty, so all you need to do is pass the objects generated by ProtoBuf to Netty. The ProtoBuf version used here is v2, which includes three keywords: required, optional, and repeated, each providing constraints on the properties within the transmitted message.\nAkka Actor Architecture The Actor architecture implements single-threaded business logic, eliminating the need to lock common properties during development. Through internal message communication, data processing proceeds in an orderly manner. Akka cluster provides dynamic load balancing, allowing for parallel expansion. In other words, if a server can\u0026rsquo;t handle the concurrency, simply configure one or more new servers and add them to the cluster for load balancing.\nConfiguration Table Information Stored in Zookeeper By reading Excel data table information into Java code, converting it into binary, and placing it in Zookeeper, configuration table hot updates can be achieved, making it possible to read it at any time.\nData Cached in Memory after Server Startup, Periodically Flushed into the Database The game server does not directly manipulate the database, but rather operates on data in memory. The data in memory is updated to the database at regular intervals. Consequently, even in cases of very high concurrent I/O, modifications are made only to the data in memory and do not directly affect the database.\nProblems Existing in Both Systems Intelligent Customer Service Inefficient Oracle Joins for Extracting Reports, Lack of Read-Write Separation The reports in the intelligent customer service system are real-time and are written in a very long SQL query using union. As a result, the query speed is very slow. In the production environment, selecting a time interval of more than 14 days and checking multiple report evaluation items leads to a query time of over 30 seconds. This means the SQL query took nearly 30 seconds to execute. We always talked about optimizing it, but in the end, we didn\u0026rsquo;t come up with any effective solutions.\nLater, I also encountered some reports. Generally, raw and unprocessed data is sent to another log collection library through a message queue, which may be called a data warehouse. Then, another system extracts and aggregates data from the data warehouse.\nAnother approach is to only query data before today when extracting reports, and then execute a scheduled task after 24:00 at the end of each day to update report data.\nOf course, all of these measures result in the inability to display the latest report data in real time, which is also a trade-off.\nPoorly Designed Chat Record Logging Each row in the chat record table contains various information about the sender and the chat session, storing too many states (because there are special messages like chat record evaluations, the structure has undergone significant changes). It is possible that initially only text was considered, then images were added (which support HTML and have HTML injection risks), and later the \u0026ldquo;Guess You Want to Ask\u0026rdquo; bubbles were introduced. However, \u0026ldquo;Guess You Want to Ask\u0026rdquo; itself is not included in the chat record, requiring special handling.\nDue to a lack of refactoring, both the front-end and back-end code became very messy as development progressed.\nSLG Game Server Hot Update Issues The larger the project, the more problems we encounter. The more problems there are, the faster we want to fix and update them in the production environment. Thanks to Java\u0026rsquo;s inheritance feature, we can achieve seamless hot updates for online players by inheriting a class with business logic, rewriting a problematic function, and correcting it with the correct business logic. However, this cannot cover every online problem. In addition to business logic classes, there are also data processing and storage classes, which cannot be hot updated because they are closely associated with the logic of scheduled data writing. Some business logic written by developers in data processing and storage classes cannot be hot updated.\nAdditionally, some properties have been marked with the private identifier, making it impossible to directly retrieve them. Reflection must be used to access them.\nCommunication Between Nodes Akka Actor is single-threaded, but this does not mean the entire system is single-threaded. To improve efficiency, we have divided the system into different Actors based on business logic and functionality modules, such as the gateway Gate, the outer city sandbox World, the inner city player Home, the alliance Alliance, and the global ranking Rank. However, as a result, some data that should have been shared by multiple nodes needs to be synchronized using internal messages.\nFor example, there is an operation activity related to a person attacking a monster on the sandbox, which adds points to themselves and their alliance. In this case, the World, Home, and Alliance nodes each need to store a copy of the activity\u0026rsquo;s start and end times. Of course, there is another way, which is to allocate a JSON object on Zookeeper to store the current activity information. However, if all complex activities use this method, Zookeeper will end up storing too much rarely used data.\nOther Systems Intelligent Customer Service Edge System: Knowledge Base System The original intention was to extract the linguistic information of the intelligent customer service as a separate subsystem. However, due to the tight association between the linguistic information and the core of the intelligent customer service, it was not possible to separate them.\nTo implement fuzzy queries, Elasticsearch (ES) was used as the storage database. However, there is a contradiction between relational databases and non-relational databases. Relational databases are convenient for managing data and reducing data redundancy but lose the ability to perform fuzzy queries and inverted indexing in ES. Using only a non-relational database would prevent direct associations with tables in other databases within the system, necessitating the use of services to obtain resources and increasing system overhead. If both a relational database like Oracle and a non-relational database like ES store a copy, the problem of data synchronization arises. It would require scheduled tasks to synchronize the two databases, and even the need for discrimination between the two databases, similar to version control systems like Git and SVN.\nGame Server: Operations GM Sending patches to the live servers, replacing the implementation of a specific method in a specific class on the live servers, thereby achieving seamless hot updates for players. Sending Groovy scripts to the live servers and executing business logic written in Groovy on the live servers. ","permalink":"https://windypath.com/en/posts/compare_web_with_game_server/","summary":"\u003ctable\u003e\n\u003cthead\u003e\n\u003ctr\u003e\n\u003cth style=\"text-align:center\"\u003eProject\u003c/th\u003e\n\u003cth style=\"text-align:center\"\u003eIntelligent Customer Service\u003c/th\u003e\n\u003cth style=\"text-align:center\"\u003eWeb Crawler\u003c/th\u003e\n\u003cth style=\"text-align:center\"\u003eSLG Game\u003c/th\u003e\n\u003c/tr\u003e\n\u003c/thead\u003e\n\u003ctbody\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eLanguage\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eJava\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003ePython\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eKotlin\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eModel\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eAsynchronous Event Driven\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eThere may not be a discernible model\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eActor Model\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eTransmission Protocol\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eHTTP\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eHTTP\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eTCP + Netty\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eTransmission Structure\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eJSON\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eJSON\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eProtobuf\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eDatabase\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eOracle, Redis\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eMongoDB\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eMySQL, Redis\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eDatabase Framework\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eMyBatis\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003ePython Library (similar to JDBC)\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eHibernate\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eCache Architecture\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eRedis for Admin Login Status\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003ePossibly only caching page numbers\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eAll game data is cached, periodically written to the database\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eConfiguration Information\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eOnly \u003ccode\u003eapplication.properties\u003c/code\u003e\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003e\u003ccode\u003econfig.ini\u003c/code\u003e\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eZookeeper, pre-loading design table information into ZK\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eConcurrency\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eNo concurrency (so no need for locks)\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003ePython multi-threading for simultaneous web crawling\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eNo concurrency, Actor model ensures only one task at a time\u003c/td\u003e\n\u003c/tr\u003e\n\u003ctr\u003e\n\u003ctd style=\"text-align:center\"\u003eHot Reload\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eDirectly restart\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eN/A\u003c/td\u003e\n\u003ctd style=\"text-align:center\"\u003eInherit a method from a certain class, replace the online class\u003c/td\u003e\n\u003c/tr\u003e\n\u003c/tbody\u003e\n\u003c/table\u003e","title":"Traditional Software Server vs. Game Server Architecture Differences"},{"content":"Born in the mid-1990s, male, from FJNU (Fujian Normal University), a native of Xiamen, Fujian, currently residing in Shanghai.\nAs a child, I always lost in computer games. Suddenly, I became interested in web pages. I would randomly modify saved web pages and open them to see the text change. It was incredibly exciting. In order to have unlimited time using computers, I decisively applied for a major in computer science.\nNever did I imagine that I would end up working as a game server developer. Two and a half years have passed in the project team of \u0026ldquo;Game of Thrones: Winter is Coming\u0026rdquo; Asia-Pacific version. I independently maintained the server for as long as half a year, becoming the \u0026ldquo;Guardian of the North Kingdom.\u0026rdquo;\nHere, I document the process of my step-by-step growth.\nContact Email: windypathblog@gmail.com\nTelegram: @windypath\n","permalink":"https://windypath.com/en/about/","summary":"Born in the mid-1990s, male, from FJNU (Fujian Normal University), a native of Xiamen, Fujian, currently residing in Shanghai.\nAs a child, I always lost in computer games. Suddenly, I became interested in web pages. I would randomly modify saved web pages and open them to see the text change. It was incredibly exciting. In order to have unlimited time using computers, I decisively applied for a major in computer science.","title":"About"},{"content":"Recently The Illustrated Happiness Trap: How to Stop Struggling and Start Living Honor Yourself: The Inner Art of Giving and Receiving The ONE Thing: The Surprisingly Simple Truth About Extraordinary Results Favorite Computer Systems: A Programmer\u0026#39;s Perspective (3rd Edition) The Illustrated Happiness Trap: How to Stop Struggling and Start Living Life Is Worth Living (Chinese Edition) The Courage to Be Disliked ","permalink":"https://windypath.com/en/mybooks/","summary":"Recently The Illustrated Happiness Trap: How to Stop Struggling and Start Living Honor Yourself: The Inner Art of Giving and Receiving The ONE Thing: The Surprisingly Simple Truth About Extraordinary Results Favorite Computer Systems: A Programmer\u0026#39;s Perspective (3rd Edition) The Illustrated Happiness Trap: How to Stop Struggling and Start Living Life Is Worth Living (Chinese Edition) The Courage to Be Disliked ","title":"My Books"},{"content":" ","permalink":"https://windypath.com/en/myfriends/","summary":" ","title":"My Friends"}]